File Reading , Reverse Direction

Peter Hansen peter at
Fri Jul 27 09:14:24 CEST 2001

Ratnakar Malla wrote:
> [I'm running] Windows 2000.
> what I really wanted was some sort of "tail " kind of functionality.
> Unfortunately, there is no "tail" command in Windows. 

True, but I've had "tail" on all my DOS and Windows systems for a
decade.  If this is just to run on your own system, dig up an 
implementation of "tail" and save yourself the trouble of
reinventing the wheel.

> I was just wondering,
> if there is any better way than reading the entire file into memory.

Probably, but "better" is pretty much open to interpretation.
Do you mean faster?  Not likely to do better than readlines().  
Less memory-hungry?  Definitely possible.  More aesthetically 
appealing?  Get over it. :-)

> Anyways thanx for your reply. I am sticking with readlines()

You might find xreadlines() useful, or not.  (Only in the 2.1 release.  
Check the docs for module xreadlines.)  Unfortunately, I just tried 
slicing it and it doesn't like that (as clearly documented). :-(

If you are really worried about both performance and memory
consumption, but have a little certainty about the length
of the lines, you could use seek() to position a little 
way back from the end of the file (largest line length times
two plus some safety margin), then apply readlines()[-2:]

>>> f = open('autoexec.bat')
>>>, 2)     # position 50 bytes before EOF
>>> f.readlines()[-2:]
['set pythonhome=c:\\a\\python\n', 'doskey >nul\n']

Peter Hansen, P.Eng.
peter at

More information about the Python-list mailing list