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.
Python code
17 linesimport 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
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
- Write specific columns using `csv.DictWriter` with `fieldnames` and `restval` for missing keys.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.