Verified Commit 18907f40 authored by Jakob Moser's avatar Jakob Moser
Browse files

Add IO helper to read and write files and standard streams

parent f5f38472
Loading
Loading
Loading
Loading

src/coliverter/io.py

0 → 100644
+22 −0
Original line number Diff line number Diff line
import sys
from pathlib import Path


def read(path: Path | None) -> str:
    """
    Read and return the UTF-8 encoded text contents of the file at `path`, or from stdin, if the path is None.
    """
    with path.open("r", encoding="utf-8") if path else sys.stdin as f:
        return f.read()


def write(data: str | bytes, path: Path | None) -> None:
    """
    Write the given data (either text or bytes) into the file at `path`, or to stdout, if the path is None.
    """
    if isinstance(data, str):
        with path.open("w", encoding="utf-8") if path else sys.stdout as f:
            f.write(data)
    else:
        with path.open("wb") if path else sys.stdout.buffer as f:
            f.write(data)