SyntaxStudy
Sign Up
Python CSV Reading & Writing
Python Intermediate 9 min read

CSV Reading & Writing

CSV Reading & Writing

Python's csv module handles the quirks of comma-separated value files — quoted fields, embedded commas, and different delimiters.

Reading CSV

import csv

with open("data.csv", "r", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)
    print(header)
    for row in reader:
        print(row)   # list of strings

DictReader

with open("data.csv", "r", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])  # access by column name

Writing CSV

with open("output.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age", "city"])
    writer.writerows([
        ["Alice", 30, "New York"],
        ["Bob",   25, "London"],
    ])

DictWriter

fields = ["name", "age", "city"]
with open("output.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=fields)
    writer.writeheader()
    writer.writerow({"name": "Carol", "age": 28, "city": "Tokyo"})

Custom Dialect

with open("pipe.csv", "r", newline="") as f:
    reader = csv.reader(f, delimiter="|", quotechar="'")
Example
import csv, io

# Simulate CSV in memory
raw = "name,score,grade
Alice,95,A
Bob,82,B
Carol,78,C"
buf = io.StringIO(raw)
reader = csv.DictReader(buf)
for row in reader:
    print(f"{row['name']:10} scored {row['score']} ({row['grade']})")
Pro Tip

Always pass newline="" when opening CSV files — the csv module handles its own line termination. Omitting it can cause blank rows on Windows.