File Reading , Reverse Direction

Kannan Vijayan kav062 at yahoo.com
Fri Jul 27 17:08:36 EDT 2001


Ratnakar Malla <rmalla1 at lsu.edu> wrote in message news:<3B60F7EC.5275E026 at lsu.edu>...
> Hi,
> I need to read from a very long file. But the only information I am
> interested is
> 2 lines at the bottom of the file.
> 1) Can i read the file in the reverse direction , so that I dont lose
> time?
> 2) If so how??
> 3) I tried the normal way, but looks like, it is taking lot of time.
> Thanx,
> Ratnakar Malla
> 
> --

A modification of Peter Hansen's code:

i = -4096
file.seek(i, 2)
lines = file.readlines()
while len(lines) <= 2:
    i -= 4096
    file.seek(i, 2)
    lines = file.readlines()
lines = lines[-2:]

The 4096 is about 1-4 pages on most filesystems, so it should be
reasonably fast, and incur about the same amount of overhead as
seeking -50.

It's multiple seeks, but if your'e dealing with large files, it's
better than going headfirst through the lines.

-kannan



More information about the Python-list mailing list