Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is file object in python an iterable

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?

like image 332
Shengjie Avatar asked Jun 07 '13 23:06

Shengjie


People also ask

Is file an iterable object?

Yes, file objects are iterators. Like all iterators, you can only loop over them once, after which the iterator is exhausted.

Which Python object is iterable?

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.

What type of object is a file in Python?

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.

Is String object iterable in Python?

The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case).


1 Answers

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.

like image 199
jamylak Avatar answered Oct 10 '22 20:10

jamylak