Skip to content

Instantly share code, notes, and snippets.

@elephantum
Created June 2, 2010 20:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elephantum/422946 to your computer and use it in GitHub Desktop.
Save elephantum/422946 to your computer and use it in GitHub Desktop.
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