Which method is better when reading text line by line?

method one:

with open("test_read.txt") as f:
    for i, v in enumerate(f):
	print i, ":", v
	print "-" * 50

Method Two:

with open("test_read.txt") as f:
    for i, v in enumerate(f.readlines()):
	print i, ":", v
	print "-" * 50

Explanation: 1. The for i, v in enumerate(f) statement converts the file object into an iterable object. Since it is an iterable object, only one item is loaded at a time, and the interpreter will not put all items into memory, thus saving resources. Before python 2.3, the f.xreadlines() method was used to read large files. It has the same function as xrange, processing iter(object), but after 2.3, the official clearly used for line in f to read large files.

2. The for i, v in enumerate(f.readlines()) statement is similar to the first one, but it executes f.readlines() first, directly storing all the list of line items in the file object into memory, above them Do a cyclic read. Therefore, the first statement is used when reading large files. Generally, both small files can be used.

Guess you like

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