The only new syntax this unit. A CSV file is plain text — commas between fields, a new line for each record. Today you get one into Python and print the first five rows. That’s the whole goal.
Focus on what split does to one line of text. That’s the whole trick. Enrolled in our Runestone course? Open it from there so your progress counts.
Big Data, with one foot back in Programs. This is the sixth visit to Unit 1’s abstraction ladder: the same bits look like commas in a text editor and like a grid in a spreadsheet.
name,grade,club,commute_min Maya,10,Robotics,12 Leo,9,Soccer,25Now open the same file in a spreadsheet: a neat table. Same bits, different lens. Your program sees the text editor version — so that’s the one you have to understand.
A CSV (comma-separated values) file stores a table as text. Each line is a record. A delimiter — here, the comma — separates the fields. The first line is usually the header row: the field names, not data. Turning that text into a list your program can use is called parsing.
Step 1 — by hand, so you see it. Read the lines, split each one on commas:
with open("clubs.csv") as f: lines = f.read().splitlines() # one string per line header = lines[0].split(",") # ['name', 'grade', 'club', 'commute_min'] rows = [] for line in lines[1:]: # skip the header rows.append(line.split(","))
Step 2 — the grown-up tool. split breaks on names like
"Ortiz, Jr." (try it below). Python’s csv module handles quoted commas
correctly, so from here on, use it:
import csv with open("clubs.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f)) # each row is a dictionary print("Rows loaded:", len(rows)) for row in rows[:5]: print(row["name"], row["club"]) # fields by name, not position
row["commute_min"] is "12",
not 12. Convert before doing math: int(row["commute_min"]). That one line is the
most common fix of the unit.
This is the raw file. Step through what Python does to it. Then edit the text — add a row, delete a comma — and parse again.
File paths are not a learning objective. Put the CSV in the same folder as your
.py file, paste this, change the file name, and run.
import csv
FILE = "club-signups.csv" # same folder as this .py file
with open(FILE, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
print("Rows loaded:", len(rows))
print("Fields:", list(rows[0].keys()))
for row in rows[:5]:
print(row)
club-signups.csv vs club_signups.csv). Check
the folder before you check your code.Five questions. Python on this page counts from 0.
Government open-data portals, sports statistics, weather records, school enrollment numbers — most public datasets are offered as CSV, because any program and any spreadsheet can read plain text. Learning to load one means you can now ask questions of almost any public data. That’s a real power, and the rest of this unit is about using it honestly.