Automate everyday tasks with Python · Lesson 6 of 14

CSV files with the csv module

Read and write CSV files with csv.reader, DictReader and DictWriter, handle commas inside fields and semicolon files, and total a column.

About 16 minutes · code runs in your browser, nothing to install

CSV (comma-separated values) is the plain-text table format that every spreadsheet program can open and save. Each line is a row, and commas separate the columns. The first line usually holds the column names.

Splitting lines on commas yourself breaks as soon as a value contains a comma, such as "Smith, Anna". Python's csv module handles quotes and commas for you. Always open CSV files with newline="" (let the csv module deal with line endings) and encoding="utf-8".

Reading rows

csv.reader gives each row as a list of strings. next(reader) takes the first row, the header, off the top.

Pythoneditable
import csv

with open("sales.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)
    print(header)
    for row in reader:
        print(row)
Output
['date', 'city', 'product', 'amount']
['2026-03-01', 'Lisbon', 'tea', '12.50']
['2026-03-01', 'Oslo', 'coffee', '8.00']
['2026-03-02', 'Lisbon', 'coffee', '9.50']
['2026-03-03', 'Seoul', 'tea', '15.00']
['2026-03-03', 'Oslo', 'tea', '7.25']

Rows as dictionaries: DictReader

csv.DictReader uses the header to turn each row into a dictionary, so you can write row["amount"] instead of remembering that the amount is column 3. All values are strings, so convert numbers with float() or int() before calculating.

Pythoneditable
import csv

totals = {}
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        city = row["city"]
        totals[city] = totals.get(city, 0) + float(row["amount"])

for city in sorted(totals):
    print(f"{city:8} {totals[city]:6.2f}")
print(f"{'Total':8} {sum(totals.values()):6.2f}")
Output
Lisbon    22.00
Oslo      15.25
Seoul     15.00
Total     52.25

Writing a CSV file: DictWriter

csv.DictWriter writes dictionaries as rows. Give it the column names with fieldnames, call writeheader() once, then writerow() for each row. Values that contain a comma are put in quotes automatically.

Pythoneditable
import csv

people = [
    {"name": "Smith, Anna", "city": "Dublin", "age": 34},
    {"name": "Kim Min-jun", "city": "Busan", "age": 29},
]

with open("people.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "city", "age"])
    writer.writeheader()
    writer.writerows(people)

with open("people.csv", encoding="utf-8") as f:
    print(f.read().strip())
Output
name,city,age
"Smith, Anna",Dublin,34
Kim Min-jun,Busan,29
Watch out: Forgetting newline="" when writing on Windows gives an empty line between every row when the file is opened in a spreadsheet. With newline="" the file is correct on every system.

Semicolons and other separators

Spreadsheet programs in many European countries save CSV files with semicolons, because the comma is the decimal sign there (12,50). Pass delimiter=";" to read them, and swap the decimal comma for a dot before converting.

Pythoneditable
import csv

with open("prices.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f, delimiter=";"):
        price = float(row["price"].replace(",", "."))
        print(row["item"], price * 2)
Output
bread 4.8
cheese 13.5

✎ Exercise

Read sales.csv and write only the rows where product is tea into tea.csv, with the columns date, city and amount (in that order). Then print tea.csv.

Hint: Keep rows with r["product"] == "tea". DictWriter needs extrasaction="ignore" to skip the product key, or build new dictionaries with only the three columns.

Your codewrite your answer, then Run
import csv
# your code here

Expected output:

date,city,amount
2026-03-01,Lisbon,12.50
2026-03-03,Seoul,15.00
2026-03-03,Oslo,7.25
Show a solution
Solutioneditable
import csv

with open("sales.csv", newline="", encoding="utf-8") as f:
    rows = [r for r in csv.DictReader(f) if r["product"] == "tea"]

with open("tea.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["date", "city", "amount"], extrasaction="ignore")
    writer.writeheader()
    writer.writerows(rows)

with open("tea.csv", encoding="utf-8") as f:
    print(f.read().strip())
Output
date,city,amount
2026-03-01,Lisbon,12.50
2026-03-03,Seoul,15.00
2026-03-03,Oslo,7.25

Check yourself

1. Why use the csv module instead of line.split(",")?

2. What type are the values in a row from DictReader?

3. Which argument reads a file whose columns are separated by semicolons?

Spotted a mistake on this page? Tell us