Skip to content

Instantly share code, notes, and snippets.

@rahulrajaram
Created October 6, 2019 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahulrajaram/4882c15e515cf8c80b3506e40cce085d to your computer and use it in GitHub Desktop.
Save rahulrajaram/4882c15e515cf8c80b3506e40cce085d to your computer and use it in GitHub Desktop.
`tail` implementation in Python
"""
Script implements:
tail FILE_NAME NUMBER_OF_LINES_TO_TAIL
"""
import sys
def seek_eof(file):
file.seek(0, 2)
def eof_value(file):
current = file.tell()
seek_eof(file)
eof = file.tell()
file.seek(current)
return eof
def current_char(file):
return file.read(1)
def seek_to_nth_line_from_eof(file, n):
seek_eof(file)
newlines = 0
i = 0
eof = file.tell()
while newlines < n:
if current_char(file) == b'\n':
newlines += 1
i -= 1
file.seek(i - 1, 2)
file.seek(i + 1, 2)
def tail(file_name, n):
with open(file_name, 'rb') as file:
seek_to_nth_line_from_eof(file, n)
tailed = file.read(eof_value(file) - file.tell())
print(tailed.decode('utf-8').strip())
tail(sys.argv[1], int(sys.argv[2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment