Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Python - recreate head/tail functionality
import os
def head(filename, count=1):
"""
This one is fairly trivial to implement but it is here for completeness.
"""
with open(filename, 'r') as f:
lines = [f.readline() for line in xrange(1, count+1)]
return filter(len, lines)
def tail(filename, count=1, offset=1024):
"""
A more efficent way of getting the last few lines of a file.
Depending on the length of your lines, you will want to modify offset
to get better performance.
"""
f_size = os.stat(filename).st_size
if f_size == 0:
return []
with open(filename, 'r') as f:
if f_size <= offset:
offset = int(f_size / 2)
while True:
seek_to = min(f_size - offset, 0)
f.seek(seek_to)
lines = f.readlines()
# Empty file
if seek_to <= 0 and len(lines) == 0:
return []
# count is larger than lines in file
if seek_to == 0 and len(lines) < count:
return lines
# Standard case
if len(lines) >= (count + 1):
return lines[count * -1:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment