Python Read/Write CSV
CSV (comma-separated values) files are plain-text tables that every spreadsheet and database can export. Python’s built-in csv module reads and writes them correctly, including the tricky cases such as commas inside quoted values.
- Write rows with csv.writer
- Read rows with csv.reader
- Use column names with DictReader and DictWriter
- Summarise CSV data
Write a CSV file
Open the file with newline="" (the csv module handles line endings itself), then write rows as lists.
import csv rows = [ ["name", "city", "score"], ["Asha", "Pune", 91], ["Ravi", "Delhi", 78], ["Meena", "Mumbai, MH", 85],]with open("students.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerows(rows) print(open("students.csv", encoding="utf-8").read())name,city,score Asha,Pune,91 Ravi,Delhi,78 Meena,"Mumbai, MH",85
Notice that "Mumbai, MH" was wrapped in quotes automatically, because it contains a comma.
Without newline="", files written on Windows get an extra blank line between rows.
Read a CSV file
csv.reader returns each row as a list of strings:
import csv with open("students.csv", newline="", encoding="utf-8") as f: reader = csv.reader(f) header = next(reader) # first row print(header) for row in reader: print(row)['name', 'city', 'score'] ['Asha', 'Pune', '91'] ['Ravi', 'Delhi', '78'] ['Meena', 'Mumbai, MH', '85']
DictReader: rows as dictionaries
DictReader uses the header row as keys, so you can write row["score"] instead of row[2]:
import csv with open("students.csv", newline="", encoding="utf-8") as f: for row in csv.DictReader(f): print(row["name"], "scored", row["score"])Asha scored 91 Ravi scored 78 Meena scored 85
DictWriter
import csv results = [ {"test": "login", "status": "pass", "ms": 812}, {"test": "search", "status": "fail", "ms": 1530},]with open("results.csv", "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["test", "status", "ms"]) writer.writeheader() writer.writerows(results) print(open("results.csv", encoding="utf-8").read().strip())test,status,ms login,pass,812 search,fail,1530
Append rows
import csv with open("results.csv", "a", newline="", encoding="utf-8") as f: csv.writer(f).writerow(["checkout", "pass", 990]) with open("results.csv", newline="", encoding="utf-8") as f: print(sum(1 for _ in csv.DictReader(f)), "data rows")3 data rows
Summarise CSV data
Values come back as strings, so convert them before doing maths:
import csv with open("students.csv", newline="", encoding="utf-8") as f: students = list(csv.DictReader(f)) scores = [int(s["score"]) for s in students]top = max(students, key=lambda s: int(s["score"]))print("Average:", round(sum(scores) / len(scores), 2))print("Top:", top["name"], top["score"])print("Above 80:", [s["name"] for s in students if int(s["score"]) > 80])Average: 84.67 Top: Asha 91 Above 80: ['Asha', 'Meena']
Other delimiters
Some files use ; or tabs. Pass delimiter:
import csv, io data = "id;product;price\n1;Pen;10\n2;Bag;650\n"for row in csv.DictReader(io.StringIO(data), delimiter=";"): print(row){'id': '1', 'product': 'Pen', 'price': '10'}
{'id': '2', 'product': 'Bag', 'price': '650'}io.StringIO turns a string into a file-like object, which is handy for testing CSV code without a real file.
For large data or heavy analysis, Pandas reads CSV in one line: pd.read_csv("students.csv"). See the Pandas lesson.
Check your understanding
Predict the output
import csv, iorows = list(csv.reader(io.StringIO('a,"b,c",d\n1,2,3\n')))print(rows, len(rows[0]))[['a', 'b,c', 'd'], ['1', '2', '3']] 3
The quoted "b,c" is one field, so the first row has three values, not four.
Quick quiz
1. What type are the values csv.reader returns?
Convert numbers yourself with int() or float().
2. Why open CSV files with newline=""?
It is the documented way to open files for csv.
3. Which class gives each row as a dictionary keyed by the header?
DictReader uses the first row as field names.
Exercise: filter rows into a new file
From students.csv, write the students who scored at least 80 to toppers.csv with the same header, then print the new file.
students.csv from this lesson
name,city,score Asha,Pune,91 Meena,"Mumbai, MH",85
Hint 1
Use DictReader to read and DictWriter with reader.fieldnames to write.
import csv with open("students.csv", newline="", encoding="utf-8") as src, \ open("toppers.csv", "w", newline="", encoding="utf-8") as dst: reader = csv.DictReader(src) writer = csv.DictWriter(dst, fieldnames=reader.fieldnames) writer.writeheader() for row in reader: if int(row["score"]) >= 80: writer.writerow(row) print(open("toppers.csv", encoding="utf-8").read().strip())name,city,score Asha,Pune,91 Meena,"Mumbai, MH",85
Reading and writing happen in the same loop, so even a huge file is processed one row at a time. reader.fieldnames reuses the original header.
Program Practice
38 Python File Handling Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python CSV FAQ
How do I read a CSV file in Python?
with open("file.csv", newline="", encoding="utf-8") as f: then for row in csv.reader(f): or csv.DictReader(f) for dictionaries.
How do I skip the header row?
Call next(reader) once before the loop, or use DictReader, which consumes the header for you.
Why do I get blank lines between rows in my CSV on Windows?
The file was opened without newline="". Add it to open() when writing CSV files.
Should I use csv or pandas?
Use csv for simple reading and writing with no extra installs. Use pandas when you need filtering, grouping, statistics or Excel export.
1 thought on “Python Read/Write CSV”