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.