Python CSV · Examples
Practical Python

Python CSV Examples

Short, runnable programs that show python csv files in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python CSV Files lesson.

1Write rows with csv.writer

writerows() writes a list of lists. Values containing a comma are wrapped in quotes automatically, and numbers are converted to text.

Write rows with csv.writer
import csv

rows = [
    ["name", "city", "score"],
    ["Asha", "Pune", 82],
    ["Smith, Jane", "Leeds", 91],
]
with open("report.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

with open("report.csv") as f:
    print(f.read(), end="")
Expected outputname,city,score
Asha,Pune,82
"Smith, Jane",Leeds,91

2Write dictionaries with csv.DictWriter

fieldnames sets the column order. writeheader() writes that first line, then each dict becomes one row.

Write dictionaries with csv.DictWriter
import csv

students = [
    {"name": "Asha", "grade": "A", "age": 21},
    {"name": "Ben", "grade": "B", "age": 22},
]
with open("students.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age", "grade"])
    writer.writeheader()
    writer.writerows(students)

with open("students.csv", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], "is", row["age"], "and got", row["grade"])
Expected outputAsha is 21 and got A
Ben is 22 and got B

3Totals per category

Combine DictReader with a dictionary of running totals to summarise a spending log by category.

Totals per category
import csv
import io

expenses = io.StringIO('''date,category,amount
2024-03-01,food,12.50
2024-03-01,travel,30.00
2024-03-02,food,8.75
2024-03-03,fun,15.00
2024-03-04,travel,22.50
''')

totals = {}
for row in csv.DictReader(expenses):
    amount = float(row["amount"])
    totals[row["category"]] = totals.get(row["category"], 0) + amount

for category, amount in sorted(totals.items()):
    print(f"{category:<8}{amount:>7.2f}")
Expected outputfood      21.25
fun       15.00
travel    52.50

4Semicolon-separated files

In many countries spreadsheets save CSV with ; between values because the comma is the decimal separator. Pass delimiter=";" and fix the decimals before converting.

Semicolon-separated files
import csv
import io

data = io.StringIO("city;temp\nOslo;-3,5\nRome;14,0\n")
reader = csv.reader(data, delimiter=";")
next(reader)
for city, temp in reader:
    celsius = float(temp.replace(",", "."))
    print(city, celsius)
Expected outputOslo -3.5
Rome 14.0

Practise next

Python CSV Files exercises → Back to the lesson

Python Dictionaries examplesPython File Handling examplesWorking with JSON in Python examplesPandas Basics examples