In the previous section, we learned how to create files and write information, so we also need to learn how to use the contents of files in programs. Regarding file operations, the following table summarizes various methods.
Use the file.read([number]) method.
The code is as follows:
file=open('test.txt','w')file.write('The first written content.')file=open('test.txt','a+')file.write('The second Append the written content. ')print(file.read(8))file.close()
The output is:
First written content
The contents of the file are:
First written content. The second append is written.
It should be noted that when we read, we must ensure that the current file is open. If we close the file after writing the information, then we will not be able to read the information and an exception will occur. The exception is as follows:
Traceback(mostrecentcalllast):FileC:/Users/test.py,line6,in<module>print(file.read(8))ValueError:I/Ooperationonclosedfile.
Use the file.readline() method.
The code is as follows:
file=open('test.txt','w')file.write('The content written for the first time.')file=open('test.txt','a+')file.write('n ')file.write('Append the written content for the second time.')print(file.readline())file.close()
The output is:
First written content.
The contents of the file are:
First written content. The second append is written.
This reading method only reads one line at a time. For files with too much content, you can use this method to read line by line.
Use the file.readlines() method.
The code is as follows:
file=open('test.txt','w')file.write('The content written for the first time.')file=open('test.txt','a+')file.write('n ')file.write('Append the written content for the second time.')print(file.readlines())file.close()file=open('test.txt','r')print(file.readlines ())file.close()
The output is:
['The content written for the first time. n','Append the written content for the second time. ']
The content of the file is:
First written content. The second append is written.
When using this method, we need to pay attention to the mode used when reading: r or r+. If it is an existing file, we can read it directly. If it is a file we have just completed writing, we can first Close, and then read in r format.
Each of the three reading methods has its own merits. You can also access the subscript to read through file.seel(index), and you can also loop through the file for efficient file reading.