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

Aahz aahz at pythoncraft.com
Sat Jan 29 13:51:59 EST 2011


In article <mailman.1412.1296196161.6505.python-list at python.org>,
John O'Hagan <research at johnohagan.com> wrote:
>>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

It's a Bad Idea to mix direct file operations with the iterator API.
Use f.read() instead of f.next().
-- 
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"All problems in computer science can be solved by another level of 
indirection." --Butler Lampson


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /