-
-
Save rahulrajaram/4882c15e515cf8c80b3506e40cce085d to your computer and use it in GitHub Desktop.
`tail` implementation in Python
This file contains hidden or 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
""" | |
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