Reading text files where last line has no EOL

BlueBird phil at freehackers.org
Mon Sep 17 07:03:41 EDT 2007


I tried and failed to read text files where the last line does not
contain proper EOL. For my tests, I use a file that I create with the
equivalent of :

open('toto', 'w').write( '1234\n4567\n89AB' )


My reading code looks like this :

       l = f.readline()
        while len(l):
            self.appendLine( l )
            l = f.readline()

The last line is not returned (89AB) is never returned.

I tried with "for l in f" with similar results.

I read the doc :

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. New in version
2.3.

I've tried to do a f.seek( f.tell() ) but that did not help.

So how am I supposed to fetch that last line ?




More information about the Python-list mailing list