Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating on a file doesn't work the second time

I have a problem with iterating on a file. Here's what I type on the interpreter and the result:

>>> f = open('baby1990.html', 'rU') >>> for line in f.readlines(): ...  print(line) ...  # ... all the lines from the file appear here ... 

When I try to iterate on the same open file again I get nothing!

>>> for line in f.readlines(): ...  print(line) ...  >>> 

There is no output at all. To solve this I have to close() the file then open it again for reading! Is that normal behavior?

like image 710
MYZ Avatar asked Apr 21 '12 01:04

MYZ


1 Answers

Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using f.seek(0) to reposition to the start of the file, or to close it and then open it again which will start from the beginning of the file.

If you prefer you can use the with syntax instead which will automatically close the file for you.

e.g.,

with open('baby1990.html', 'rU') as f:   for line in f:      print line 

once this block is finished executing, the file is automatically closed for you, so you could execute this block repeatedly without explicitly closing the file yourself and read the file this way over again.

like image 102
Levon Avatar answered Oct 03 '22 18:10

Levon