how to read the last line of a huge file???

John O'Hagan research at johnohagan.com
Fri Jan 28 01:29:10 EST 2011


On Wed, 26 Jan 2011, Xavier Heruacles wrote:
> I have do some log processing which is usually huge. The length of each
> line is variable. How can I get the last line?? Don't tell me to use
> readlines or something like linecache...

file.seek takes an optional 'whence' argument which is 2 for the end, so you 
can just work back from there till you hit the first newline that has anything 
after it:


def lastline(filename):
    offset = 0
    line = ''
    with open(filename) as f:
        while True:
            offset -= 1
            f.seek(offset, 2)
            nextline = f.next()
            if nextline == '\n' and line.strip():
                return line
            else:
                line = nextline


John



More information about the Python-list mailing list