all Python 3Files & I/Oterm
csv.DictWriter
csv — writing
A CSV writer for dicts: the required fieldnames sets the column order, and writeheader() writes the header row.
Syntax
w = csv.DictWriter(f, fieldnames, restval='', extrasaction='raise'); w.writeheader()
The header is not written automatically — without writeheader() the file has no first row. A key missing from fieldnames raises ValueError; pass extrasaction='ignore' to drop extras silently. Missing keys, on the other hand, are not an error: restval is written instead, an empty string by default.
Examples
import csv
import io
out = io.StringIO()
w = csv.DictWriter(out, fieldnames=['name', 'age'], lineterminator='\n')
w.writeheader()
w.writerow({'name': 'Anna', 'age': 30})
w.writerow({'name': 'Bob'})
print(out.getvalue()) # → name,age / Anna,30 / Bob,
import csv
import io
w = csv.DictWriter(io.StringIO(), fieldnames=['name'])
try:
w.writerow({'name': 'X', 'mail': 'x@y'})
except ValueError as e:
print(e) # → dict contains fields not in fieldnames: 'mail'
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy