Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/fsutil/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
10 changes: 10 additions & 0 deletions tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
Loading