From 04c1e1b20507d5455338a3dd7c14d0b15bb85836 Mon Sep 17 00:00:00 2001 From: Lushiyao5 <321342421+Lushiyao5@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:47:59 -0700 Subject: [PATCH] Stop reading after the last requested line Assisted-by: OpenAI Codex --- src/fsutil/io.py | 11 ++++++----- tests/test_io.py | 10 ++++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/fsutil/io.py b/src/fsutil/io.py index a400a5d..5687877 100644 --- a/src/fsutil/io.py +++ b/src/fsutil/io.py @@ -78,13 +78,14 @@ def _read_file_lines_in_range( line_start = max(0, line_start + lines_count) if line_end_negative: line_end = min(line_end + lines_count, lines_count - 1) + if line_end < line_start: + return with open(path, encoding=encoding, newline="\n") as file: - file.seek(0) - line_index = 0 - for line in file: - if line_index >= line_start and line_index <= line_end: + for line_index, line in enumerate(file): + if line_index >= line_start: yield line - line_index += 1 + if line_index == line_end: + break def read_file_lines( diff --git a/tests/test_io.py b/tests/test_io.py index 1000c2d..032d8fc 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -133,6 +133,16 @@ def test_read_file_lines_range_empty_encoded_file(tmp_path, encoding): assert fsutil.read_file_lines(path, line_start=-2, encoding=encoding) == [] +def test_read_file_lines_stops_at_end_of_requested_range(tmp_path): + path = tmp_path / "log.txt" + path.write_bytes(b"first\nsecond\n" + b"later\n" * 16384 + b"\xff") + + assert fsutil.read_file_lines(path, line_start=0, line_end=1) == [ + "first", + "second", + ] + + def test_read_file_lines_count(temp_path): path = temp_path("a/b/c.txt") lines = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]