Oct 20, 2009

reading in multiple functions from the same file in Python using a for-loop and readline()

I had to read i multiple python functions from a file.

The deepest function used
for line in f:

In the outer loop I attempted to read further lines  with
f.readline()
But I didn't get any data.

A f.tell() showed, that I was already at the end of the file.


Now I've tested a little bit around:

The for loop uses the iterator protocol.

So the file is itself the iterator and does a readahead.

My question was now, what if the file is very large?. 

A test on my opensolaris box showed, that 8k are read ahead.
You can use the
f.next()
and Python reads any data in as necessary. If the end of the file
is reached, a StopIteration Exception is raised.