Standard Library

CSV Data

csv reads and writes row-shaped text data.

DictReader uses the header row as dictionary keys. The values are still strings because CSV is text.

Source

import csv
import io

text = "name,score\nAda,98\nGrace,95\n"
rows = list(csv.DictReader(io.StringIO(text)))

print(rows[0])
print(type(rows[0]["score"]).__name__)

Output

{'name': 'Ada', 'score': '98'}
str
ROWS · RECORDSidnamescore1Ada972Bo883Cy76
CSV files are rows of records; each line has the same columns in the same order.

Convert numeric fields at the boundary where the program leaves CSV text and starts doing arithmetic.

Source

print(sum(int(row["score"]) for row in rows))

Output

193

DictWriter turns dictionaries back into row-shaped text with the same column order.

Source

output = io.StringIO(newline="")
writer = csv.DictWriter(output, fieldnames=["name", "passed"])
writer.writeheader()
writer.writerow({"name": "Ada", "passed": True})

print(output.getvalue().splitlines()[1])

Output

Ada,True

Notes

See also

Run the complete example

Example code

Expected output

{'name': 'Ada', 'score': '98'}
193
Ada,True

Execution time appears here after you run the example.