Created
June 2, 2010 20:30
-
-
Save elephantum/422946 to your computer and use it in GitHub Desktop.
This file contains 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
import os | |
import itertools | |
CHUNK_SIZE = 100 | |
def read_lines_backwards(filename): | |
f = file(filename, 'rb') | |
f.seek(0, os.SEEK_END) | |
left = '' | |
while f.tell() > 0: | |
bytes_to_read = min(f.tell(), CHUNK_SIZE) | |
# read chunk and return to original position | |
f.seek(-bytes_to_read, os.SEEK_CUR) | |
buf = f.read(bytes_to_read) + left | |
f.seek(-bytes_to_read, os.SEEK_CUR) | |
lines = buf.split('\n') | |
for i in reversed(lines[1:]): | |
yield i | |
left = lines[0] | |
yield left | |
def tail(filename, n): | |
it = read_lines_backwards(filename) | |
line = it.next() | |
# skip all empty lines at the end of file | |
while line == '': | |
line = it.next() | |
res = [line] + list(itertools.islice(it, n-1)) | |
return list(reversed(res)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment