Created
October 8, 2018 10:54
-
-
Save gilankpam/3b23559ce44b1c7abab294990637e203 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
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