Search code examples
pythonfile-ioreadlines

What's the difference between "for x in file/file.readlines()"


According to the type, file is a function and file.readlines() is a list of lines. But why do these two generate the same results in the following code:

file = open("test.txt")
for x in file:
    print x

and

file = open("test.txt")
for x in file.readlines():
    print x

Solution

  • readlines() reads the entire file into a list(), over which you then iterate using for. But, you can also just iterate over the file object itself, which will cause it to read one line at a time with each iteration of the loop. That's much more efficient, since it won't store the entire file's contents in memory at once.