简体   繁体   中英

How does Python know that it has to read a file line by line when the sequence part of the for loop is a file?

Here I open the second value of the sys.argv list for reading, store the file object in variable f and then process the file line by line:

f = open(sys.argv[1])
for line in f:

How does Python know that it has to read file line by line? At first I thought that line itself has some sort of special meaning, but I could also do for xine in f: and it still works. Does Python know that it has to read a file line by line if the sequence part of the for loop is a file(or file object)?

Does Python know that it has to read a file line by line if the sequence part of the for loop is a file(or file object)?

Yes, that's how file objects were implemented in Python.

A file object is an iterator object, whose next method returns a line. Putting that in a for simply calls the next method repeatedly and what you get are lines of the file being assigned in succession to the loop variable: line , xine or any other valid assignment target.


for line in f:
    # do something with line

is synonymous to doing:

line = next(f)
# do something with line
line = next(f)
# do something with line
...
# repeat until EOF

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