Skip to content

Instantly share code, notes, and snippets.

@gilankpam
Created October 8, 2018 10:54
Show Gist options
  • Save gilankpam/3b23559ce44b1c7abab294990637e203 to your computer and use it in GitHub Desktop.
Save gilankpam/3b23559ce44b1c7abab294990637e203 to your computer and use it in GitHub Desktop.
Tail implementation in python
import io, sys, itertools
def tail(file, line_count):
BUFFER_SIZE = 1024
pos = -BUFFER_SIZE
offset = 0
result_lines = []
result_line_count = 0
while result_line_count < line_count:
file.seek(pos, io.SEEK_END)
text = file.read(BUFFER_SIZE + offset)
try:
offset = text.index(b'\n')
except ValueError:
offset = len(text)
pos = pos - BUFFER_SIZE
continue
lines = text.splitlines()[1:]
line_to_add = line_count - len(result_lines)
if len(lines) >= line_to_add:
result_lines.append(lines[-line_to_add:len(lines)])
else:
result_lines.append(lines)
result_line_count+=len(lines)
pos = pos - BUFFER_SIZE
result_lines.reverse()
flatten = list(itertools.chain.from_iterable(result_lines))
return b'\n'.join(flatten).decode('utf-8')
if __name__ == '__main__':
filename = sys.argv[1]
line = int(sys.argv[2])
with io.open(filename, 'br') as file:
print(tail(file, line))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment