Skip to content

Instantly share code, notes, and snippets.

@MondeSinxi
Created January 23, 2024 20:01
Show Gist options
  • Save MondeSinxi/118c34627668c9f9595990055795056b to your computer and use it in GitHub Desktop.
Save MondeSinxi/118c34627668c9f9595990055795056b to your computer and use it in GitHub Desktop.
Get the last n lines of a file.
from pathlib import Path
def tail(filename: str | Path, n: int) -> str:
"""
Get the last n lines of a file.
Parameters:
- filename (str | Path): The path to the file.
- n (int): The number of lines to retrieve from the end of the file.
Returns:
- str: The last n lines of the file.
Algorithm Explanation:
- We move the cursor to the end of the file using `file.seek(0, 2)`.
- We iterate backward through the file character by character to find newline characters.
- We keep track of the number of newline characters found (`count`).
- Once we reach the desired number of newline characters (n + 1), we read from the last newline character found.
Note:
- This approach efficiently retrieves the last n lines without reading the entire file into memory.
"""
if Path(filename).stat().st_size == 0:
raise IOError("File is empty")
idx = 0
count = 0
with open(filename, "rb") as file:
# Move cursor to the end of the file
file.seek(0, 2)
# Start search for new lines
while count < n + 1:
idx += 1
file.seek(-idx, 2)
if file.read(1) == b"\n":
count += 1
if file.tell() == 0:
break
data = file.read()
return data.decode("utf-8")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment