Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a for loop over a file work in Python?

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?

like image 601
0x41414141 Avatar asked Jun 11 '26 13:06

0x41414141


1 Answers

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

like image 171
Chamila Chulatunga Avatar answered Jun 13 '26 01:06

Chamila Chulatunga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!