Python · Module 8 · Lesson 21 min read

Working with CSV

CSV = comma-separated values

A simple table format that Excel, Google Sheets and databases can all read and write.

The csv module

  • csv.writer(f) with .writerow() / .writerows() writes rows as lists.
  • csv.reader(f) reads each row as a list of strings.
  • csv.DictWriter(f, fieldnames=[...]) and csv.DictReader(f) use the header row as keys, which is much easier to read.

Important details

  • Open files with newline="" when writing CSV, or you get blank lines on Windows.
  • Every value comes back as a string. Convert numbers yourself: int(row["age"]).
  • The module handles commas and quotes inside values ("Kathmandu, Nepal"), so don't split lines with .split(",") yourself.

💡 For heavy data work (filtering, grouping, charts), the pandas library is the next step.

▶️ Runs in the app.

Example

Python
import csv

people = [
    {"name": "Ana", "age": 25, "city": "Kathmandu, Nepal"},
    {"name": "Ben", "age": 31, "city": "Pokhara"},
]

with open("people.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "age", "city"])
    writer.writeheader()
    writer.writerows(people)

with open("people.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

for row in rows:
    print(row["name"], int(row["age"]) + 1, row["city"])
# Ana 26 Kathmandu, Nepal
# Ben 32 Pokhara

average = sum(int(r["age"]) for r in rows) / len(rows)
print("Average age:", average)     # 28.0