Skip to content

CSV

flpit.csv loads CSV rows into dataclasses. Columns map to fields by name, and cells are converted to the field's type (numbers, booleans, dates, enums and anything in the JSON type registry).

from dataclasses import dataclass
from typing import Annotated

from flpit.csv import CsvCol, CsvLoader, CsvOptions


@dataclass
class Person:
    name: str
    age: int
    city: Annotated[str, CsvCol("Home Town")]   # the column header differs from the field name


text = "name,age,Home Town\nAda,36,London\nGrace,45,New York\n"

people = CsvLoader.load_list(text, Person)      # eager: a FlpList[Person]
assert people.select(lambda p: p.city).to_list() == ["London", "New York"]

# Lazy: rows are converted one by one as the query is enumerated.
over_forty = CsvLoader.load_it(text, Person).where(lambda p: p.age > 40).select(lambda p: p.name)
assert over_forty.to_list() == ["Grace"]

# Other dialects: pass options.
semicolons = CsvLoader.load_list("name;age;Home Town\nAda;36;London\n", Person, CsvOptions(delimiter=";"))
assert semicolons[0].age == 36
  • CsvLoader.load_list reads everything at once and returns a FlpList.
  • CsvLoader.load_it returns a lazy FlpIt. With a file path, the file is opened when the query is enumerated and closed when it ends, and conversion errors surface during enumeration.
  • data is either CSV text or a pathlib.Path.
  • CsvCol("Header") names the column explicitly. JProp and JIgnore work the same way as in JSON.
  • CsvOptions sets the delimiter, quote and escape characters, encoding (UTF-8 with an optional byte order mark by default) and a naming policy.
  • A cell that cannot be converted raises CsvConversionError, which is a ValueError.