Is file object in python an iterable

Shengjie picture Shengjie · Jun 8, 2013 · Viewed 11.6k times · Source

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:

  1. the file object returned by open(), is it an iterable? that's why it can be used in a for loop?

  2. why loop2 doesn't get printed at all?

Answer

jamylak picture jamylak · Jun 8, 2013

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.