Advertisement
🔧 Intermediate

Python CSV – Reading and Writing CSV Files

CSV (Comma-Separated Values) is the most common format for exchanging tabular data — spreadsheets, databases, reports. Python's built-in csv module provides robust reading and writing without any third-party dependencies.

⏱️ 18 min read🎯 Intermediate📅 Updated 2026

Reading CSV Files

csv.reader reads each row as a list of strings.

Python
import csv

# Example CSV (students.csv):
# name,grade,score
# Alice,A,95
# Bob,B,82
# Charlie,A,91

with open("students.csv", "r") as f:
    reader = csv.reader(f)
    header = next(reader)     # Skip header row
    print(f"Columns: {header}")
    for row in reader:
        print(f"{row[0]}: {row[2]}")
▶ Output
Columns: ['name', 'grade', 'score'] Alice: 95 Bob: 82 Charlie: 91

DictReader – Rows as Dictionaries

csv.DictReader maps each row to a dict using the header row as keys.

Python
import csv

with open("students.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['name']} scored {row['score']} (grade {row['grade']})")
▶ Output
Alice scored 95 (grade A) Bob scored 82 (grade B) Charlie scored 91 (grade A)

Writing CSV Files

csv.writer writes lists as CSV rows.

Python
import csv

students = [
    ["name", "grade", "score"],  # header
    ["Alice", "A", 95],
    ["Bob", "B", 82],
    ["Charlie", "A", 91]
]

with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(students)

print("CSV written successfully")
▶ Output
CSV written successfully
💡
Tip

Always pass newline="" when opening CSV files on Windows to prevent extra blank lines.

Advertisement

DictWriter – Write from Dicts

Use DictWriter when your data is in dictionary form.

Python
import csv

rows = [
    {"name": "Alice", "grade": "A", "score": 95},
    {"name": "Bob",   "grade": "B", "score": 82},
]

with open("output.csv", "w", newline="") as f:
    fields = ["name", "grade", "score"]
    writer = csv.DictWriter(f, fieldnames=fields)
    writer.writeheader()     # Write column names
    writer.writerows(rows)   # Write all rows

Real-World: Analyse CSV Data

Compute statistics from a CSV without pandas.

Python
import csv

total, count = 0, 0
with open("students.csv", "r") as f:
    for row in csv.DictReader(f):
        total += int(row["score"])
        count += 1

print(f"Average score: {total/count:.1f}")
▶ Output
Average score: 89.3

Reading and Writing CSV the Right Way

CSV looks simple — comma-separated lines — but hand-parsing with .split(",") breaks the moment a field contains a comma or a quote. Python's csv module handles all those edge cases correctly.

import csv

# read as dictionaries keyed by header row
with open("data.csv", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["email"])

# write
with open("out.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "email"])
    writer.writeheader()
    writer.writerow({"name": "Ann", "email": "a@b.com"})
ClassGives you
csv.readereach row as a list
csv.DictReadereach row as a dict (uses header)

Why not split(","): a value like "Smith, John" is one quoted field with a comma inside — split wrongly cuts it in two. The csv module respects quoting and escaping. Two must-dos: always open files with newline="" (prevents blank rows on Windows), and use a with block so the file closes even on error. DictReader is usually nicest — access columns by name (row["email"]) instead of fragile numeric indices. For anything beyond simple I/O (filtering, analysis, large files), pandas.read_csv() is far more powerful.

🏋️ Practical Exercise

Read and write CSV data:

  1. Read a CSV file with csv.reader and print each row.
  2. Re-read it with csv.DictReader and access columns by name.
  3. Write a list of rows to a new CSV with csv.writer (remember newline="").
  4. Write a list of dicts with csv.DictWriter including a header row.

🔥 Challenge Exercise

Given a CSV of sales records (date, product, amount), use DictReader to load it, compute the total and average sale per product, and write a summary CSV with DictWriter. Handle a missing or malformed row gracefully without crashing. Bonus: sort the summary by total descending before writing it out.

📋 Summary

  • Python’s built-in csv module reads and writes comma-separated files.
  • csv.reader yields rows as lists; csv.DictReader yields rows as dicts keyed by header.
  • Open files with newline="" to avoid blank lines on some platforms.
  • csv.writer and csv.DictWriter handle writing; writeheader() emits the column names.
  • The delimiter argument supports tabs, semicolons, and other separators.
  • For heavy analysis, pandas’ read_csv is more powerful than the raw module.

Interview Questions on CSV Files

  • What module does Python use to work with CSV files?
  • What is the difference between csv.reader and csv.DictReader?
  • Why should you pass newline="" when opening a CSV file for writing?
  • How do you handle CSV files with different delimiters?
  • How do you write a header row with DictWriter?
  • Why might you use pandas instead of the csv module?
  • How do you handle quoted fields containing commas?

FAQ

Why do I get blank rows between lines when writing CSV? +

On Windows, the file’s own newline translation collides with the one the csv writer adds. Open the file with open(path, "w", newline="") to fix it.

When should I use the csv module versus pandas? +

Use the csv module for simple, streaming reads/writes with no extra dependencies. Use pandas when you need filtering, grouping, joins, or statistics on tabular data — it is far more convenient for analysis.

What is the difference between reader and DictReader? +

csv.reader gives each row as a list, so you access fields by index. csv.DictReader uses the header row to give each row as a dictionary, so you access fields by column name — usually clearer and safer.

How do I read a tab- or semicolon-separated file? +

Pass the separator to the reader: csv.reader(f, delimiter="\t") or delimiter=";". The same applies to the writer.