Skip to content

Instantly share code, notes, and snippets.

@mrtj
Last active April 1, 2025 10:40
Show Gist options
  • Save mrtj/2dc82607678abbe76bdb1e9082d6eda8 to your computer and use it in GitHub Desktop.
Save mrtj/2dc82607678abbe76bdb1e9082d6eda8 to your computer and use it in GitHub Desktop.
Read text file line by line in python on-demand
from os import PathLike
from typing import Iterator
def readlines(filename: PathLike) -> Iterator[str]:
"""Reads a file line by line, yielding the lines as strings.
Unlike Python's file object readlines method, this function does not read the entire file into
memory, but reads it on demand.
Args:
filename: Path to the file to be read
Returns:
Iterator yielding each line of the file as a string with trailing whitespace removed
"""
with open(filename, "rt") as f:
for line in f:
yield line.rstrip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment