Skip to content

Instantly share code, notes, and snippets.

@gjcourt
Created February 6, 2012 22:37
Show Gist options
  • Save gjcourt/1755542 to your computer and use it in GitHub Desktop.
Save gjcourt/1755542 to your computer and use it in GitHub Desktop.
Read last line of a file
def read_last_line(fd):
"""
Efficiently read the last line of a file by seeking to the
end of the file and looping backwards until the first linefeed
character is encountered. Ignores trailing newlines at the EOF
"""
# seek to the end of the file
fd.seek(0, 2)
size = fd.tell()
if size == 0:
return ''
BLOCKSIZE = min(size, 512) # bytes
pos = 0
while pos + BLOCKSIZE <= size:
# seek to next block
pos += BLOCKSIZE
fd.seek(-pos, 1)
s = fd.read()
try:
if s.index('\n') != len(s) - 1:
return '\n'.join(s.rsplit('\n', 2 if s.endswith('\n') else 1)[1:])
except ValueError:
continue
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment