Python File Reading Basics

Source: Internet
Author: User

The following example shows how to read and print the contents in the.txt text file under the current directory to the screen. Is the running result.




 


The program code is as follows:

[Python]
Rfile = open ("a.txt", 'R ')
Words = rfile. read ()
Print words
Rfile. close ()

Rfile = open ("a.txt", 'R ')
Words = rfile. read ()
Print words
Rfile. close ()
Contents. Line 2 of the code closes the file because the file should be closed after reading and writing.
Now we have learned how to open a file and read the file. Now we want to raise two questions ..
Question 1. What if the file to be read is not in the current directory? (This section uses the read. py Program)





How can we change the program by setting a directory on the top of the current directory?

 


 

The program to be compiled now is read.py.pdf, who wants to read the.txt file under the parent directory. Let's see how to change the program.

 

 

 

The program code is as follows:
[Python]
Rfile = open ("../a.txt", 'R ')
Words = rfile. read ()
Print words
Rfile. close ()

Rfile = open ("../a.txt", 'R ')
Words = rfile. read ()
Print words
Rfile. close ()
In your parent directory. (../Represents the upper-level directory in linux). The problem has been solved. We can continue.
Question 2: Can I read the content of a file in one row?
Of course, you can change the function to solve the problem. Here we will introduce the readline function of another read file. This function reads the file in one row (end with the first \ n in each row ).



The Code is as follows.

[Python]
Rfile = open ("../a.txt", 'R ')
Words = rfile. readline ()
Print words
Rfile. close ()

Rfile = open ("../a.txt", 'R ')
Words = rfile. readline ()
Print words
Rfile. close ()

The readline function reads only one row at a time! If you want to read both rows, read them twice.

 

 

 



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.