I have this piece of code
f = open('textfile.txt', 'r')
for line in f:
print line
lets just say the textfile.txt is something like this
1
2
3
4
5
How does this work? How does it know where it is in the file? I understand that it is printing over and over but why doesn't it just print the whole file over and over. I don't see how f is a range. I also assume it knows to stop at EOF?
Calling open() returns a file object - i.e. f is a file object.
File objects are their own iterators, implementing the next() method, allowing them to be used in for loops as per your example. And yes, the iterator implementation knows to stop at EOF.
Have a look at the description here, under the file.next() method details:
http://docs.python.org/2/library/stdtypes.html#bltin-file-objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With