Skip to content

Instantly share code, notes, and snippets.

@mrtj
Last active April 1, 2025 10:40
Show Gist options
  • Select an option

  • Save mrtj/2dc82607678abbe76bdb1e9082d6eda8 to your computer and use it in GitHub Desktop.

Select an option

Save mrtj/2dc82607678abbe76bdb1e9082d6eda8 to your computer and use it in GitHub Desktop.

Revisions

  1. mrtj revised this gist Apr 1, 2025. 1 changed file with 10 additions and 4 deletions.
    14 changes: 10 additions & 4 deletions readlines.py
    Original file line number Diff line number Diff line change
    @@ -1,12 +1,18 @@
    from os import PathLike
    from typing import Iterator

    def read_lines(filename: PathLike) -> Iterator[str]:
    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.
    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()
    yield line.rstrip()
  2. mrtj revised this gist Apr 1, 2025. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions readlines.py
    Original file line number Diff line number Diff line change
    @@ -4,8 +4,8 @@
    def read_lines(filename: PathLike) -> Iterator[str]:
    """Reads a file line by line, yielding the lines as strings.
    Unlike python file object's readlines method, this method does not read the entire file in the
    memory, but reads the file on demand.
    Unlike Python's file object readlines method, this function does not read
    the entire file into memory, but reads it on demand.
    """
    with open(filename, "rt") as f:
    for line in f:
  3. mrtj created this gist Apr 1, 2025.
    12 changes: 12 additions & 0 deletions readlines.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    from os import PathLike
    from typing import Iterator

    def read_lines(filename: PathLike) -> Iterator[str]:
    """Reads a file line by line, yielding the lines as strings.
    Unlike python file object's readlines method, this method does not read the entire file in the
    memory, but reads the file on demand.
    """
    with open(filename, "rt") as f:
    for line in f:
    yield line.rstrip()