简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM