How to read lines from end of a file?

Alexander Williams thantos at chancel.org
Wed Dec 22 18:27:04 EST 1999


On 22 Dec 1999 21:52:31 +0100, Stig Bjorlykke <stigb at tihlde.org> wrote:
>open FILE, "/tmp/file";
>foreach (reverse <FILE>) { ... }
>
>I am using it to get the latest entries in a log file.

Thought about:

    >>> data = open("filename").readlines()
    >>> data.reverse()
    >>> for lne in data:
    >>>     ...

Admittedly this gets rather hairy for long log file analysis since it
has to slurp up the whole thing into memory; alternately, you can try
opening it in binary mode, seek to the end, start skipping backwards
until you find the last CR, then begin loading characters into a
buffer in reverse order.  Probably not as effortless, but much, much
lighter on the memory requirements.

-- 
Alexander Williams (thantos at gw.total-web.net)           | In the End,
  "Join the secret struggle for the soul of the world." | Oblivion
  Nobilis, a new Kind of RPG                            | Always
  http://www.chancel.org                                | Wins



More information about the Python-list mailing list