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_listreads everything at once and returns aFlpList.CsvLoader.load_itreturns a lazyFlpIt. With a file path, the file is opened when the query is enumerated and closed when it ends, and conversion errors surface during enumeration.datais either CSV text or apathlib.Path.CsvCol("Header")names the column explicitly.JPropandJIgnorework the same way as in JSON.CsvOptionssets 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 aValueError.