Read file from bottom

Peter Hansen peter at engcorp.com
Mon May 13 20:25:32 EDT 2002


Julia Bell wrote:
> 
> Good idea; I never thought of something like that.
> 
> My initial reaction is that I don't know I exactly how many lines frm the
> bottom I want.  (I currently read the lines, search for data on the lines
> that meets some trigger criterion, and then start processing the data from
> there.)  

Often the simplest solution to this problem is to examine the usual
lines in the file (this works best if it's like a log file, for example,
where most lines are of similar length) and simply use seek() to start
N lines multiplied by M bytes per line from the end of the file.
Then just read forwards until you find your trigger.  It depends on a
few things, but if you know the trigger will generally be within 100
lines of the end, and most lines are about 65 characters, just start
100*(65+1) bytes backwards (counting newlines) and go forward...

-Peter



More information about the Python-list mailing list