There are three kinds of functions in Python that read files:
- Read ()
- ReadLine ()
- ReadLines ()
However, what is the difference between them, when used in peacetime always encountered, summed up today.
0. Pre-work
First, create a new file Read.txt, for examples of actual effects
Hellowelcome to my worldyou are so clever !!!
1. Read ()
The read (size) method reads a size byte from the current location of the file, and the default (no parameter) indicates that the read to the end of the file is returned as a string object
The test procedure is as follows:
import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f: content = f.read() print(content) print(type(content))
Here are two points to note:
I used OS-related operations, which eliminates the hassle of having to enter the full path of the file.
You have to form with open file as F: This habit, that is, after the operation is finished, let it automatically close the files.
Hellowelcome to my worldyou are so clever !!!<class ‘str‘>Process finished with exit code 0
2. ReadLine ()
Reads one line at a time, consumes less memory (for large files), and returns a String object
Test procedure:
import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f: content = f.readline() print(content) print(type(content))
Output Result:
Hello<class ‘str‘>Process finished with exit code 0
3. ReadLines ()
Reads all the rows of the file, saves it in a list variable, and each behavior in the list is an element that returns a list object.
Test procedure:
import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f: content = f.readlines() print(content) print(type(content))
Output Result:
[‘Hello\n‘, ‘welcome to my world\n‘, ‘1234\n‘, ‘you are so clever !!!‘]<class ‘list‘>Process finished with exit code 0
Usage of read (), ReadLine (), and ReadLines () in Python read-write files