Codzy

CSV files

A CSV file is a table saved as text: each line is a row, and values are separated by commas. They're everywhere: Excel exports, open data, bank statements…

The csv module reads and writes them. csv.DictReader returns each row as a dictionary with the column names as keys, and csv.writer writes rows with writerow(). Careful: values you read are always text, so convert them with int() or float().

import csv
import io

data = "name,score\nSara,18\nAli,12\n"
for row in csv.DictReader(io.StringIO(data)):
    print(row["name"], int(row["score"]) + 1)

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["city", "temp"])
    writer.writerow(["Paris", 12])

with open("out.csv") as f:
    print(f.read())

Start the lesson