PythonMastery

How do I write a CSV file in Python?

Open the file with newline='' and use csv.DictWriter: writeheader() once, then writerows(). The csv module quotes commas and line breaks inside values for you.

Use csv.DictWriter. Tell it the column names once, write the header, then hand it your rows as dictionaries.

python
import csv

orders = [
    {"id": "A-1001", "customer": "Ada", "total": 49.99},
    {"id": "A-1002", "customer": "Grace", "total": 120.00},
]

with open("orders.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["id", "customer", "total"])
    writer.writeheader()
    writer.writerows(orders)

with open("orders.csv", encoding="utf-8") as f:
    print(f.read())
output
id,customer,total
A-1001,Ada,49.99
A-1002,Grace,120.0

Notice 120.0: the writer calls str() on each value. If the file is going to a person, format it yourself first, for example f"{total:.2f}".

Don't build the line with string joins

",".join(values) works right up until a value contains a comma. The csv module quotes it for you, which is the whole reason to use it.

python
import csv, io

with io.StringIO() as out:                  # stands in for an open file
    writer = csv.writer(out)
    writer.writerow(["Hopper, Grace", 'She said "hi"', 120])
    print(out.getvalue())
output
"Hopper, Grace","She said ""hi""",120

Any spreadsheet program reads that back as three cells, exactly as written.

The two things that bite

To add rows to a file that already exists, open it with "a" instead of "w" and skip writeheader().

Go deeper: CSV, JSON, and JSONL — Structured Text Done Right, File I/O, Pathlib, and Large Files

More short answers

all questions