Reputation: 1197
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)?
Upvotes: 0
Views: 72
Reputation: 78564
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
Upvotes: 2