Skip to content

Instantly share code, notes, and snippets.

@willmcgugan
Created March 2, 2024 16:10
Show Gist options
  • Save willmcgugan/252781fa98bede695d7c0b183a39652c to your computer and use it in GitHub Desktop.
Save willmcgugan/252781fa98bede695d7c0b183a39652c to your computer and use it in GitHub Desktop.
Get the last lines from a file
import mmap
def get_last_lines(path: str, count: int) -> list[str]:
"""Get count last lines from a file."""
with open(path, "r+b") as text_file:
text_mmap = mmap.mmap(text_file.fileno(), 0, mmap.ACCESS_READ)
position = len(text_mmap)
while count and (position := text_mmap.rfind(b"\n", 0, position)) != -1:
count -= 1
return text_mmap[position + 1 :].decode("utf-8").split("\n")
if __name__ == "__main__":
import sys
last = get_last_lines(sys.argv[1], 5)
print(last)
print(len(last))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment