I have a file "test.txt":
this is 1st line
this is 2nd line
this is 3rd line
the following code
lines = open("test.txt", 'r')
for line in lines:
print "loop 1:"+line
for line in lines:
print "loop 2:"+line
only prints:
loop 1:this is 1st line
loop 1:this is 2nd line
loop 1:this is 3rd line
It doesn't print loop2 at all.
Two questions:
the file object returned by open(), is it an iterable? that's why it can be used in a for loop?
why loop2 doesn't get printed at all?
Yes, file objects are iterators. Like all iterators, you can only loop over them once, after which the iterator is exhausted.
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
What is the File Object? Python file object provides methods and attributes to access and manipulate files. Using file objects, we can read or write any files. Whenever we open a file to perform any operations on it, Python returns a file object.
The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case).
It is not only an iterable, it is an iterator, which is why it can only traverse the file once. You may reset the file cursor with .seek(0)
as many have suggested but you should, in most cases, only iterate a file once.
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