Reading CSV Files
csv.reader reads each row as a list of strings.
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]}")DictReader – Rows as Dictionaries
csv.DictReader maps each row to a dict using the header row as keys.
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']})")Writing CSV Files
csv.writer writes lists as CSV rows.
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")Always pass newline="" when opening CSV files on Windows to prevent extra blank lines.
DictWriter – Write from Dicts
Use DictWriter when your data is in dictionary form.
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 rowsReal-World: Analyse CSV Data
Compute statistics from a CSV without pandas.
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}")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"})
| Class | Gives you |
|---|---|
csv.reader | each row as a list |
csv.DictReader | each 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:
- Read a CSV file with
csv.readerand print each row. - Re-read it with
csv.DictReaderand access columns by name. - Write a list of rows to a new CSV with
csv.writer(remembernewline=""). - Write a list of dicts with
csv.DictWriterincluding 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
csvmodule reads and writes comma-separated files. csv.readeryields rows as lists;csv.DictReaderyields rows as dicts keyed by header.- Open files with
newline=""to avoid blank lines on some platforms. csv.writerandcsv.DictWriterhandle writing;writeheader()emits the column names.- The
delimiterargument supports tabs, semicolons, and other separators. - For heavy analysis, pandas’
read_csvis 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.readerandcsv.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
csvmodule? - How do you handle quoted fields containing commas?
Related Topics
FAQ
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.
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.
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.
Pass the separator to the reader: csv.reader(f, delimiter="\t") or delimiter=";". The same applies to the writer.

