File Reading , Reverse Direction

Peter Hansen peter at
Fri Jul 27 08:01:24 CEST 2001

Ratnakar Malla wrote:
> 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?

Do you really want to read in "reverse"?  To me that implies getting
each byte in reverse order, which would require reversing the lines
again after finding the "first" two... Or do you just want to read
line-by-line, in reverse?

> 2) If so how??

How about this?

   lastTwoLinesAsList = open('somefile').readlines()[-2:]

> 3) I tried the normal way, but looks like, it is taking lot of time.

What is "normal"?  Maybe your code is not the most efficient

You could also use "seek" to find the end of the file, then 
go backwards a few dozen bytes at a time, grabbing blobs of
data until you found the third-last newline (or the second last,
if the file did not end with a newline), then return everything
after that point.  This would be awkward, largely unreadable,
bug-prone, and might take a while to develop.

Or how about calling out to "tail"?

   import os
   lastTwoLinesAsString = os.popen('tail -2 somefile').read()

You might also want to post a sample of your code, and mention
which platform you are on, so feedback might be a little more
relevant to your situation...

Peter Hansen, P.Eng.
peter at

More information about the Python-list mailing list