Skip to content

CSV Reader

This is a simple helper to read and write CSV files.

Example

from nupd.inputs.csv import CsvInput

csv = CsvInput[MyEntryInfo]("input-file.csv")

entry_infos = csv.read(lambda x: MyEntryInfo(**x))
csv.write(entries_info, serialize=lambda x: x.model_dump(mode="json"))

API reference

CsvInput dataclass

CsvInput(
    file: PathLike[str], kwargs: dict[str, Any] = dict()
)

Bases: ABCInput[GEntryInfo]

file instance-attribute

file: PathLike[str]

kwargs class-attribute instance-attribute

kwargs: dict[str, Any] = field(default_factory=dict)

Kwargs, passed to csv functions.

read

read(
    parse: Callable[[Mapping[str, str]], GEntryInfo],
) -> Iterable[GEntryInfo]

Read provided CSV file.

Parameters:

  • parse
    (Callable[[Mapping[str, str]], GEntryInfo]) –

    Function, that parses a row to an EntryInfo.

    Warning

    Item in a line can be an empty string instead of a None. We don't handle it, as "not optional" value would be opt-in and it is pretty annoying to handle that. You have to handle it by yourself.

write

write(
    entries: Iterable[GEntryInfo],
    serialize: Callable[[GEntryInfo], Mapping[str, str]],
) -> None

Write all entries to the provided file.

All entries are sorted by their ID for reproducibility.

Parameters:

  • serialize
    (Callable[[GEntryInfo], Mapping[str, str]]) –

    Function, that is called to serialize an EntryInfo to a dict, that we can then put into CSV.