question re file as sequence

Peter Otten __peter__ at web.de
Sun Jul 11 05:15:48 EDT 2004


Christopher T King wrote:

> Unfortunately, when f is used as an iterator, it seems to move the file
> pointer to the end of the file (question for the higher ups: why? StringIO

>From the documentation of file.next():

"""In order to make a for loop the most efficient way of looping over the
lines of a file (a very common operation), the next() method uses a hidden
read-ahead buffer. As a consequence of using a read-ahead buffer, combining
next() with other file methods (like readline()) does not work right.
However, using seek() to reposition the file to an absolute position will
flush the read-ahead buffer."""

http://docs.python.org/lib/bltin-file-objects.html

However, you cannot use tell() to find the absolute position, as it returns
the position at the end of the read-ahead buffer - tell() is just a thin
wrapper around the underlying C file. The easiest workaround becomes then

def readline(fileIter):
    try:
        return fileIter.next()
    except StopIteration:
        return ""


Peter




More information about the Python-list mailing list