Reading a text file backwards

Jeremy Bowers jerf at jerf.org
Thu Sep 30 21:09:42 EDT 2004


On Thu, 30 Sep 2004 17:41:14 -0700, Graham  Fawcett wrote:

> It's just shifting the burden perhaps, but if you're on a Unix system
> you should be able to use tac(1) to reverse your file a bit faster:
> 
> import os
> for line in os.popen('tac myfile.txt'):
> #do something with the line

It probably isn't shifting the burden; they probably do it right.

Doing it right involves reading the file in chunks backwards, and scanning
backwards for newlines, but getting it right when lines cross boundaries,
while perhaps not *hard*, is exactly the kind of tricky programming it is
best to do once... preferably somebody else's once. :-) 

This way you don't read the file twice, as the first time can take a while.



More information about the Python-list mailing list