The difference and usage of read(), readline() and readlines() in Python

It is well known that there are three commonly used methods for reading files in python: read(), readline(), readlines(). Today, I forgot their differences when looking at the project. When I used to read a book, I thought this thing was very simple. I glanced at it at a glance, but when I used it, I only knew there were so many methods, but I didn't understand its principle and usage. Maybe, there is no permanent memory, and there is no intention to remember it at all. Without further ado, let's take a look at the detailed introduction:

Suppose a.txt

1. The read([size]) method

read([size])The method reads size bytes from the current position of the file. If there is no parameter size, it means reading until the end of the file, and its range is a string object.

f = open("a.txt")
lines = f.read()
print lines
print(type(lines))
f.close()

Output result:

Hello
Welcome
What is the fuck...
 <type ' str ' > #string type

2. The readline() method

It can be seen from the literal meaning that this method reads one line at a time, so it takes up less memory when reading, which is more suitable for large files. This method returns a string object.

f = open("a.txt")
line = f.readline()
print(type(line))
while line:
 print line,
 line = f.readline()
f.close()

Output result:

<type 'str'>
Hello
Welcome
What is the fuck...

3. The readlines() method reads all lines of the entire file and saves them in a list variable, with each line as an element, but reading large files will take up more memory

f = open("a.txt")
lines = f.readlines()
print(type(lines))
for line in lines:
 print line,
f.close()

Output result:

1 <type 'list'>
2 Hello
3 Welcome
4 What is the fuck...

Fourth, the linecache module

Of course, you can also use the linecache module for special needs. For example, if you want to output the nth line of a file:

# print line 2
text = linecache.getline(‘a.txt',2)
print text,

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325017235&siteId=291194637