Lesson 4: Reading CSV Data
CSV (Comma-Separated Values) is the most common data file format in the world. Spreadsheets, databases, and sensors all export CSV. Python's built-in csv module and the popular pandas library let you load and work with CSV data in just a few lines.
Key Concepts
What Is CSV?
A plain text file where each row is a record and commas separate the fields:
name,score,city
Alex,92,Tulsa
Brooke,85,OKC
The first row is usually the header.
Reading CSV with csv module
import csv
with open("data.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["score"])
Simulating CSV with Strings
When you can't open a file, you can simulate CSV using io.StringIO:
import csv, io
csv_text = 'name,score\nAlex,92'
reader = csv.DictReader(io.StringIO(csv_text))
Working with the Data
Once loaded, treat each row as a dictionary. Collect scores into a list, compute averages, filter rows with if statements — all the Python skills from Lessons 1-3 apply directly.
🔬 Interactive Lab: CSV Table Viewer
Paste CSV text into the box and click Load. The data renders as a table with column totals.
✅ Check Your Understanding
1. What does CSV stand for?
2. In a CSV file, what does the first row usually contain?
3. What Python module is built-in for reading CSV files?