Skip to main content
Albero Academy

CSV Files

Read and write comma-separated data with the csv module.

File Handling9 min

CSV (comma-separated values) is the universal tabular format — every spreadsheet and database can export it. Python's csv module reads and writes it correctly, handling the tricky cases (quoted fields, commas inside values) you'd get wrong by splitting on commas yourself.

Reading with DictReader

DictReader turns each row into a dict keyed by the header row — far clearer than positional indexing:

reading rows as dicts
import csv
with open("students.csv", newline="") as f:
reader = csv.DictReader(f) # uses the header row for keys
for row in reader:
print(row["name"], row["package"]) # access by column name

Writing with DictWriter

writing rows
with open("out.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "package"])
writer.writeheader()
writer.writerow({"name": "Ana", "package": 7.5})
writer.writerows([
{"name": "Ravi", "package": 9.0},
{"name": "Kai", "package": 6.5},
])

Key takeaways

  1. 01The csv module handles quoting and delimiters correctly — don't split on commas yourself.
  2. 02DictReader maps each row to a dict keyed by the header; DictWriter writes them back.
  3. 03Always pass newline="" when opening CSV files.
  4. 04writeheader() then writerow(s) for output.
  5. 05For heavy analysis, pandas.read_csv is more powerful.

Finished this chapter?

Mark it complete to track your progress through Python.