How to read lines from end of a file?

Darrell news at dorb.com
Wed Dec 22 19:12:52 EST 1999


import sys

def readLinesFromEnd(fn,maxLen):
    """
    Read lines from the end of a file up to a max.

    fn:: file name to read from
    maxLen:: max number of bytes to read
    """
    fp=open(fn)
        # seek to the end
    fp.seek(0,2)
        # seek back from the end
    fp.seek(-min(maxLen,fp.tell()),2)
        # Dump the first line
        # It might be chopped off
    lines=fp.readlines()[1:]
    return lines

def main():
    print readLinesFromEnd(sys.argv[1],1000)

main()

--
--Darrell
"Alexander Williams" <thantos at chancel.org> wrote in message
news:slrn862nn8.6rk.thantos at chancel.org...
> 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
> --
> http://www.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list