Reading a text file backwards

Andrew Dalke adalke at mindspring.com
Thu Sep 30 17:53:21 EDT 2004


Jay wrote:
> Only, I want to iterate backwards, starting with the last line of the file.
> Can anybody suggest a simple way of doing this? Do I need to jump around
> with myfile.seek() and use myfile.readline() ?

Python Cookbook has a recipe.  Or two.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/276149
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/120686

I've not looked at them to judge the quality

Another approach is to read the lines forwards and save
the starting line position.  Then iterate backwards
through the positions, seek to it and read a line.

def find_offsets(infile):
     offsets = []
     offset = 0
     for line in infile:
         offsets.append(offset)
         offset += len(line)
     return offsets

def iter_backwards(infile):
     # make sure it's seekable and at the start
     infile.seek(0)
     offsets = find_offsets(infile)
     for offset in offsets[::-1]:
         infile.seek(offset)
         yield infile.readline()

for line in iter_backwards(open("spam.py")):
     print repr(line)

This won't work on MS Windows because of the
'\r\n' -> '\n' conversion.  You would instead
need something like

def find_offsets(infile):
     offsets = []
     while 1:
         offset = infile.tell()
         if not infile.readline():
             break
         offsets.append(offset)
     return offsets


Just submitted this solution to the cookbook.

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list