// python · beginner
Working with CSV Files in Python: Read, Write and Analyse Data
Learn how to read and write CSV spreadsheet files in Python with the csv module, use DictReader and DictWriter, convert numbers, and calculate totals and averages.
CSV (comma-separated values) is the simplest and most common way to store table data, such as marks, prices, sports results and survey answers. Every spreadsheet program, including Excel and Google Sheets, can open and save CSV files, which makes them the perfect bridge between your Python programs and the real world.
You should be comfortable with reading and writing text files before starting this guide.
What a CSV file looks like
A CSV file is plain text. Each line is a row, and commas separate the columns. The first line is usually a header with the column names. Save this as marks.csv:
name,subject,mark
Ava,Maths,82
Leo,Maths,67
Mia,Science,91
Sam,Science,58
Why not just use split(“,”)?
You could read each line and call .split(","). It works for simple files, but breaks as soon as a value contains a comma, such as "Smith, Jo". CSV files handle that with quotes, and Python’s built-in csv module understands all those rules for you. Use it.
Reading rows with csv.reader
import csv
with open("marks.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader) # the first row: the column names
for row in reader:
print(row)
['Ava', 'Maths', '82']
['Leo', 'Maths', '67']
['Mia', 'Science', '91']
['Sam', 'Science', '58']
Each row is a list of strings. next(reader) reads one row, which is a handy way to skip the header. Always open CSV files with newline="", as the Python documentation recommends; it stops blank lines appearing between rows on Windows.
Reading rows as dictionaries with DictReader
Remembering that row[2] is the mark gets confusing. csv.DictReader uses the header to turn each row into a dictionary:
import csv
with open("marks.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(f"{row['name']} got {row['mark']} in {row['subject']}")
row['mark'] is much clearer than row[2], and your code keeps working if someone adds a new column.
Converting numbers
Everything read from a CSV file is text. Convert numbers before doing maths, or you’ll get a TypeError (or silently join strings together):
import csv
total = 0
count = 0
with open("marks.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
total += int(row["mark"])
count += 1
print(f"Average mark: {total / count:.1f}") # Average mark: 74.5
Real-world files often contain a blank or broken value. Wrap the conversion in try and except so one bad row doesn’t stop the whole program:
try:
mark = int(row["mark"])
except ValueError:
print(f"Skipping bad mark for {row['name']}")
Grouping and analysing
Combining DictReader with a dictionary lets you summarise data by category:
import csv
by_subject = {}
with open("marks.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
by_subject.setdefault(row["subject"], []).append(int(row["mark"]))
for subject, marks in by_subject.items():
average = sum(marks) / len(marks)
print(f"{subject}: {len(marks)} students, average {average:.1f}, top {max(marks)}")
Maths: 2 students, average 74.5, top 82
Science: 2 students, average 74.5, top 91
setdefault(key, []) returns the list for that subject, creating an empty one the first time. It’s a tidy way to collect items into groups.
Writing CSV files
Use csv.writer and its writerow method. Numbers are converted to text for you:
import csv
rows = [
["name", "score"],
["Ava", 120],
["Leo", 95],
]
with open("scores.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(rows)
writerows writes a whole list of rows at once. Remember that "w" replaces the file; use "a" to add rows to the end.
Writing dictionaries with DictWriter
If your data is already a list of dictionaries, DictWriter is the natural choice:
import csv
results = [
{"name": "Ava", "mark": 82, "grade": "A"},
{"name": "Leo", "mark": 67, "grade": "C"},
]
with open("results.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "mark", "grade"])
writer.writeheader()
writer.writerows(results)
fieldnames sets the column order, and writeheader() writes the header row. Open results.csv in a spreadsheet program to check it.
Mini project: a grade report
This reads marks.csv, works out a grade for each student and saves a new file:
import csv
def grade_for(mark):
if mark >= 80:
return "A"
if mark >= 70:
return "B"
if mark >= 60:
return "C"
return "D"
report = []
with open("marks.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
mark = int(row["mark"])
report.append({"name": row["name"], "mark": mark, "grade": grade_for(mark)})
report.sort(key=lambda r: r["mark"], reverse=True)
with open("report.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "mark", "grade"])
writer.writeheader()
writer.writerows(report)
for r in report:
print(f"{r['name']:<6}{r['mark']:>4} {r['grade']}")
report.sort(key=lambda r: r["mark"], reverse=True) sorts the students by mark, highest first. A lambda is a tiny one-line function; here it tells sort which value to compare. Challenge: add a final row to the printed report showing the class average.
Key points
- CSV files are plain-text tables; the first row is usually a header.
- Use the
csvmodule, not.split(","), and open files withnewline="". csv.DictReadergives each row as a dictionary keyed by the header.- Values are read as strings; convert with
int()orfloat(). csv.writerandcsv.DictWritersave rows;writeheader()adds column names.
Next: use code other people have already written in Python Modules and pip. New to the terminal? Read Command Line Basics.