← Back to Python, page 3

python-0058 · Medium mid

Read and write CSV files correctly, including quoting and dictionaries.

Use the csv module rather than splitting on commas, because fields may contain commas, quotes or newlines. Open files with newline='' and an explicit encoding. DictReader and DictWriter map rows to dictionaries keyed by the header, which keeps code readable when columns change order.

Full answer
python
import csv, io
buf = io.StringIO(newline="")
w = csv.DictWriter(buf, fieldnames=["name", "city", "note"])
w.writeheader()
w.writerow({"name": "Asha", "city": "Pune", "note": "likes SQL, Python"})
w.writerow({"name": "Ben", "city": "Leeds", "note": 'said "hi"'})
text = buf.getvalue()
print(text)
rows = list(csv.DictReader(io.StringIO(text, newline="")))
print(rows[0]["note"], "|", rows[1]["note"])
print(text.splitlines()[1].split(","))

Output:

text
name,city,note
Asha,Pune,"likes SQL, Python"
Ben,Leeds,"said ""hi"""

likes SQL, Python | said "hi"
['Asha', 'Pune', '"likes SQL', ' Python"']

The writer quoted the note containing a comma and doubled the quotes inside Ben's note, following the CSV rules. Reading back with DictReader restores the original values exactly. The last line shows why naive splitting fails: it breaks Asha's note into two fields. With real files, open(path, newline='', encoding='utf-8') avoids blank lines on Windows and encoding surprises. For large data analysis, pandas or DuckDB read CSV faster, but the csv module is dependable for streaming rows.

python
import csv, io
buf = io.StringIO(newline="")
w = csv.DictWriter(buf, fieldnames=["name", "city", "note"])
w.writeheader()
w.writerow({"name": "Asha", "city": "Pune", "note": "likes SQL, Python"})
w.writerow({"name": "Ben", "city": "Leeds", "note": 'said "hi"'})
text = buf.getvalue()
print(text)
rows = list(csv.DictReader(io.StringIO(text, newline="")))
print(rows[0]["note"], "|", rows[1]["note"])
print(text.splitlines()[1].split(","))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Use the csv module, not split
  • newline='' and explicit encoding
  • DictReader and DictWriter use headers
  • Quoting handles commas and quotes

Common mistakes

  • Splitting lines on commas
  • Opening CSV files without newline=''

Follow-ups

  • How would you process a CSV larger than memory?
  • How do you handle different delimiters?

Tips

  • Show the failing split