PythonMastery
Python programs · Files · beginner

Write a CSV file in Python

Save a list of dictionaries as a CSV file with csv.DictWriter: write the header, then the rows. Also shows csv.writer for lists.

csv.DictWriter turns a list of dictionaries into CSV rows. You tell it the column names once, and it writes the values of each dictionary in that order.

The program

python
import csv

people = [
    {"name": "Ada", "city": "London", "score": 95},
    {"name": "Linus", "city": "Helsinki, Finland", "score": 87},
    {"name": "Grace", "city": "New York", "score": 91},
]

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

# show what was saved
with open("people.csv", encoding="utf-8") as f:
    print(f.read(), end="")
output
name,city,score
Ada,London,95
Linus,"Helsinki, Finland",87
Grace,New York,91

How it works

Rows as lists

If your rows are lists instead of dictionaries, use csv.writer and write the header as a normal row:

python
import csv

rows = [
    ["Hedy", "Vienna", 88],
    ["Alan", "London", 93],
]

with open("people.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "city", "score"])
    writer.writerows(rows)

with open("people.csv", encoding="utf-8") as f:
    print(f.read(), end="")
output
name,city,score
Hedy,Vienna,88
Alan,London,93

Related programs: Read a CSV file.

Learn the idea: CSV, JSON, and JSONL: Structured Text Done Right, File I/O, Pathlib, and Large Files

A longer explanation: How do I write a CSV file in Python?