Write CSV file with csv DictWriter in Python

Write a list of dictionaries to a CSV file using Python's csv.DictWriter, including a header row.

Easy Python 3.9+ Aug 9, 2026 Files & data 16 views 0 copies

Python code

17 lines
Python 3.9+
import csv
from pathlib import Path

fieldnames = ["name", "city", "age"]
rows = [
    {"name": "Alice", "city": "New York", "age": 30},
    {"name": "Bob", "city": "Los Angeles", "age": 25},
    {"name": "Charlie", "city": "Chicago", "age": 35},
]

path = Path("people.csv")
with path.open("w", newline="") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)

print(path.read_text())

Output

stdout
name,city,age
Alice,New York,30
Bob,Los Angeles,25
Charlie,Chicago,35

How it works

The csv.DictWriter class maps dictionaries to CSV rows using the fieldnames list, which determines column order and the header. Calling writeheader() writes the header row, then writerows() writes each dictionary in order. Opening the file with newline='' prevents CSV parsing issues on Windows. Using pathlib.Path.open ensures the file is closed automatically.

Common mistakes

  • Forgetting to call `writeheader()` so the header row is missing.
  • Using `newline=''` is required to avoid blank lines between rows on Windows.
  • Passing a dictionary with missing keys causes a `ValueError`; use `extrasaction='ignore'` or ensure all keys exist.

Variations

  1. Write specific columns using `csv.DictWriter` with `fieldnames` and `restval` for missing keys.
  2. Use `csv.writer` with `writerow` for explicit list rows instead of dictionaries.

Real-world use cases

  • Exporting user data from a database into a CSV report for a client.
  • Generating a CSV file of product inventory for a spreadsheet upload to an e-commerce platform.
  • Writing model results to CSV for further analysis in a data pipeline.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.