How do I read and write CSV files in Python?

· Category: Python Programming

Short answer

Python's built-in csv module provides csv.reader and csv.writer for basic CSV handling, and csv.DictReader / csv.DictWriter for working with dictionaries keyed by column headers.

Steps

  1. Open the file in text mode.
  2. Create a reader or writer object.
  3. Iterate over rows or write rows.
import csv

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

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

Tips

  • Always open CSV files with newline="" to prevent extra blank lines on Windows.
  • Use DictReader to access columns by name instead of index.
  • Specify delimiter, quotechar, and quoting for non-standard formats.
# DictReader
with open("data.csv", "r", encoding="utf-8", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["age"])

Common issues

  • Missing newline="" causes double line endings on Windows.
  • Mixing text and binary modes causes csv module errors.
  • Very large CSV files may require streaming line-by-line instead of loading everything into memory.