Created
January 23, 2024 20:01
-
-
Save MondeSinxi/118c34627668c9f9595990055795056b to your computer and use it in GitHub Desktop.
Get the last n lines of a file.
This file contains 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
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