Created
February 6, 2012 22:37
-
-
Save gjcourt/1755542 to your computer and use it in GitHub Desktop.
Read last line of a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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