Skip to content

Module 13 · File Handling — topic 10 of 15

CSV files

Comma-separated values with the csv module: reader and writer, DictReader and DictWriter, quoting of commas and quotes, newline="", and summarising tabular data.

Beginner 10 min read·Lesson 203 of 306 in Python Programming

Learning objectives

  • Read and write CSV with csv.reader and csv.writer
  • Use DictReader and DictWriter with headers
  • Aggregate data from a CSV file

Definition

A CSV (comma-separated values) file stores a table as text, one row per line, with fields separated by commas. Python's csv module reads and writes CSV correctly, including fields that contain commas, quotes or newlines.

Introduction

Spreadsheets, bank statements and data exports are often CSV files. Splitting lines on commas yourself breaks as soon as a field contains a comma — the csv module handles that properly.

Why it matters

CSV is the most common exchange format for tabular data. Reading it correctly is a basic skill for automation and data work.

Detailed explanation

Always open CSV files with newline="" so the csv module controls line endings itself, and specify the encoding.

csv.reader(f) yields each row as a list of strings; csv.writer(f).writerow(list) writes one row and writerows(rows) writes many.

csv.DictReader(f) uses the first row as field names and yields each row as a dictionary. csv.DictWriter(f, fieldnames=[...]) writes dictionaries; call writeheader() first.

Fields containing commas, quotes or newlines are wrapped in double quotes, and embedded quotes are doubled — the module does this automatically.

Every value read from a CSV file is a string. Convert with int() or float() before calculating.

Other delimiters (semicolon, tab) are supported with delimiter=";" or "\t".

For heavy data analysis, pandas.read_csv is common, but the csv module needs no installation and is perfect for scripts.

Syntax

Python
import csv
with open("data.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], int(row["marks"]))
  • Open with newline="".
  • DictReader uses the header row.
  • Values are strings; convert them.

Code examples

Writing and reading rows

Python
import csv
rows = [["name", "city", "marks"], ["Asha", "Pune", 91], ["Ravi", "Delhi, NCR", 78]]
with open("students.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
with open("students.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)
Output
['name', 'city', 'marks']
['Asha', 'Pune', '91']
['Ravi', 'Delhi, NCR', '78']

Automatic quoting

Python
import csv
with open("p.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["item", "note"])
w.writeheader()
w.writerow({"item": "pen", "note": "blue, fine tip"})
w.writerow({"item": "book", "note": 'says "hello"'})
with open("p.csv", encoding="utf-8") as f:
print(f.read().splitlines())
Output
['item,note', 'pen,"blue, fine tip"', 'book,"says ""hello"""']

More examples

Summarising sales by region

Python
import csv
from collections import defaultdict
csv_text = "region,product,amount\nNorth,pen,120\nSouth,book,300\nNorth,book,250\nSouth,pen,80\nNorth,pen,60\n"
with open("sales.csv", "w", newline="", encoding="utf-8") as f:
f.write(csv_text)
totals = defaultdict(int)
with open("sales.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
totals[row["region"]] += int(row["amount"])
print(dict(totals))
with open("summary.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["region", "total"])
w.writerows(sorted(totals.items()))
with open("summary.csv", encoding="utf-8") as f:
print(f.read().splitlines())
Output
{'North': 430, 'South': 380}
['region,total', 'North,430', 'South,380']

Step-by-step explanation

  • DictReader turns each data row into a dictionary keyed by the header.
  • amount is converted with int() before adding.
  • The summary is written as a new CSV with its own header row.

Expected output

Running “Summarising sales by region” prints exactly:

TextOutput
{'North': 430, 'South': 380}
['region,total', 'North,430', 'South,380']

Practical applications

  • Importing bank statements into a budgeting script.
  • Exporting reports for spreadsheet users.

Best practices

  • Use the csv module, never manual splitting.
  • Prefer DictReader/DictWriter for readability.
  • Convert types explicitly.

Common mistakes

Splitting on commas manually

Avoid

fields = line.split(",")

Prefer

for fields in csv.reader(f): ...

"Delhi, NCR" would be split into two fields.

Forgetting newline=""

Avoid

open("out.csv", "w")

Prefer

open("out.csv", "w", newline="", encoding="utf-8")

On Windows you get blank lines between rows.

Important notes

  • Excel may expect encoding="utf-8-sig" to detect UTF-8 correctly.

Key takeaways

  • csv.reader/writer handle lists; DictReader/DictWriter handle dictionaries.
  • Open CSV files with newline="".
  • All values read are strings.

Try it yourself

  1. 1
    Read a CSV of students and write a new CSV containing only those with marks above 80.
  2. 2
    Compute the average of a numeric column in a CSV file.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic