Lesson 35 / 49

CSV & JSON Files

Read and write CSV and JSON files with the standard library using csv.DictReader, json.load and json.dump.

Reading CSV

The csv module reads rows as lists (or dicts with DictReader) — no manual split(",") needed.

import csv

with open("people.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

Reading & writing JSON

json.dumps/json.loads convert between Python objects and JSON text; json.dump/json.load work directly with files.

import json

data = {"name": "Ada", "skills": ["python", "math"]}
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

with open("data.json") as f:
    loaded = json.load(f)
print(loaded["skills"])