Working with text and files
Read and write CSV
Use the csv module to store and load rows while preserving commas in fields.
Lesson 31 of 63
Reading: about 2 min
Lesson + practice: about 14 min
Difficulty: Beginner
On this page4 sections
CSV stores tabular rows as text. Use Python’s csv module instead of joining fields with commas yourself: the module handles quoted fields that contain commas.
For file practice, download the Python practice files v1.0.0 bundle. The examples write their own files, so the samples stay unchanged. Work on a copy if you edit a sample.
import csv
from pathlib import Path
path = Path("my_sessions.csv")
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["subject", "minutes"])
writer.writerow(["Python, basics", 25])
with path.open("r", newline="", encoding="utf-8") as file:
rows = list(csv.reader(file))
print(rows)[['subject', 'minutes'], ['Python, basics', '25']]
CSV fields are text when read
csv.reader returns strings. Convert a numeric field with int() before arithmetic. Opening in write mode replaces an existing file, so work in a practice folder.
import csv
from io import StringIO
data = StringIO("subject,minutes\nPython,25\nSQL,40\n")
reader = csv.reader(data)
next(reader) # Skip the header.
total = sum(int(row[1]) for row in reader)
print(total)65
Why this works
A CSV row is a sequence of fields. csv.writer adds quoting when a field contains a comma, so "Python, basics" remains one field when csv.reader loads it. The reader returns text values, including "25"; convert numeric fields before calculations.
Practice
Add a second data row to my_sessions.csv. Read the file and calculate the total minutes from its data rows, skipping the header as in the worked extension. Convert each minutes field to int. Then read the sample sessions.csv from the practice bundle the same way; its minutes add up to 75.
Why is the value 25 read back as "25"?
Reveal answer
CSV is text; csv.reader returns field values as strings.
Try another case
After csv.reader loads the data row, what type is its minutes field and what should you do before adding it?
Check your answer
Reveal answer
It is str. Convert it with int() before arithmetic.
Your progress
Reveal the check answer or reach the end to complete this lesson.