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?
It is not only an iterable, it is an iterator [1], 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.
[1]: The "file" object is of class TextIOBase
which is a subclass of IoBase
, and IoBase
supports the iterator protocol.