There are three magic read operations in python: read, readline and readlines
read() : Read the entire file contents at once. It is recommended to use the read(size) method, the larger the size, the longer the running time
readline() : Read one line at a time. Used when the memory is not enough, generally not used
readlines() : Read the entire file content at once, and return to the list by line, so that we can traverse
Generally, we use read() for small files. If you are not sure of the size, you can set a size. For large files, use readlines()
1) We first use read to read a small file completely, the code is as follows:
f = open('test.py', 'r') print(f.read()) f.close() # Remember to close after use
Take a look at the result of running:
We see that this is a simple program that prints Hello World!
At the same time, I also feel that the small task of printing small files is indeed faster to hand over to read
2) Then look at readline, the code:
f = open('test.py', 'r') print(f.readline()) f.close()
operation result:
Sure enough, as the name suggests, it only miserably prints a line for me
My original file test.py has five lines of text, so I need to print five times after finishing a test.py, which is a little troublesome
3) Finally, look at readlines, the code:
f = open('test.py', 'r') print(f.readlines()) f.close()
operation result:
It really puts our content into a list, even spaces and \n are preserved
Then we write a loop to iterate over it:
f = open('test.py', 'r') for line in f.readlines(): print(line, end="") f.close()
Because print will automatically wrap, we use end="" to cancel
The operation is as shown in the figure:
In this way, we get the same content as using read.
However, readlines still has certain advantages in reading configuration files.