reading the last line of a file

Fredrik Lundh fredrik at pythonware.com
Thu Sep 8 06:38:44 EDT 2005


Martin Franklin wrote:

> Ok, in that case stick to your shell based solution, although 100
> megabytes does not sound that large to me I guess it is relative
> to the system you are running on :) (I have over a gig of memory here)

since the file is gzipped, you need to read all of it to get the last line.
however, replacing

    last_line = logfile.readlines()[-1]

with a plain

    for last_line in logfile: pass

avoids storing the entire file in memory.

(note that seek() actually reads the file in 1024 blocks until it gets
to the right location; reading via a line iterator only seems to be
marginally slower.  zcat|tail is a LOT faster.  ymmv.)

</F> 






More information about the Python-list mailing list