Last active
April 1, 2025 10:40
-
-
Save mrtj/2dc82607678abbe76bdb1e9082d6eda8 to your computer and use it in GitHub Desktop.
Read text file line by line in python on-demand
This file contains hidden or 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 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