Read file from bottom

Bob Horvath usenet at horvath.com
Wed May 15 22:23:53 EDT 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.)
> 
> 

How about a iterator way of doing it (python 2.2)...


def lastlines(fname,n=10):

    lines = []

    for line in open(fname):

       if len(lines) == n:
          lines = lines[1:]

       lines.append(line)

    return lines




More information about the Python-list mailing list