June 2019
Beginner to intermediate
770 pages
19h 24m
English
We can load simple, sequential objects from a CSV file with a loop like the following:
with (Path.cwd() / "data" / "ch10_blackjack_1.csv").open() as source: reader = csv.DictReader(source) assert set(reader.fieldnames) == set(GameStat._fields) for gs in (GameStat(**r) for r in reader): print( gs )
We've defined a reader for our file. As we know that our file has a proper heading, we can use DictReader. This will use the first row to define the attribute names. We can now construct the GameStat objects from the rows in the CSV file. We've used a generator expression to build rows.
In this case, we've assumed that the column names match the attribute names of our GameStat class definition. We can, if necessary, ...
Read now
Unlock full access