Read file from bottom

Sean 'Shaleh' Perry shalehperry at attbi.com
Mon May 13 16:31:33 EDT 2002


On 13-May-2002 Julia Bell wrote:
> I'm currently using
>     line = input_handle.readline()
> to read individual lines from an input file; however, I'm only generally
> interested in the last few lines of the line (not the preceeding several
> thousand lines).
> 
> Is there an efficient (and relatively easy - I'm new to Python) way of
> reading the file from the last line backward instead of the first line
> forward?
> 
> (I do not want to read the entire file using readlines because it could
> overwhelm the memory.)
> 

unfortunately, no.  The file does not store information about the number of
lines or even lines in general.

A common practice is to read the file once just to count the lines and then
read it again with this knowledge in hand.  For instnace once you know that you
have 1234 lines in a file you can do:

desired = 15 # number of lines we want
# count is set to 1234 from previous code
end = count - desired
i = 0
while i < end: # eat the lines we do not care about
    line = file.readline()
    i = i + 1
# now deal with the 'desired' lines







More information about the Python-list mailing list