Unit 5 · Data · Lesson 5.3

Reading a CSV

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.

Big Idea 2 — DataCED 2.4 · Only new syntax this unit

Before this lesson — read on Runestone

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.

1

Where We Are

People→ Bits→ Programs→ Internet→ Security→ Big Data→ Impact

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.

2

The Hook

Open a CSV in a text editor. No grid, no cells. Just this:
name,grade,club,commute_min
Maya,10,Robotics,12
Leo,9,Soccer,25
Now 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.
3

The Idea

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
Every value comes in as a string. 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.
AP Pseudocode doesn’t read files. On the exam, the data is already in a list. So everything after loading — the traversal, the counting — is what the exam tests, and it’s Unit 3 material you already know.
4

Try It — Parse It Yourself

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.

Starter block — copy this, don’t retype it

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)
FileNotFoundError? Ninety percent of the time the CSV isn’t in the same folder as your program, or the name is off by one character (club-signups.csv vs club_signups.csv). Check the folder before you check your code.
5

Vocabulary

CSV Big Data
Comma-separated values: a plain-text file where each line is a record and commas separate the fields.
delimiter Big Data
The character that separates fields in a line of data — a comma in a CSV.
header row Big Data
The first line of a CSV, naming each field. It is not a record.
parsing Big Data
Turning raw text into structured data a program can use — such as a list of records.
6

Check

Five questions. Python on this page counts from 0.

0 of 5 answered
7

Impact Check

The world runs on CSV

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.

8

Connections

Came from 2.6–2.7 — strings and indexing. split is a string method; parts[2] is indexing.
Came from Unit 1 — the abstraction ladder — commas in a text editor, a grid in a spreadsheet, the same bits.
Next in 5.4 — the file is loaded. Now: what do you actually want to know?
Returns in Lab 5.5 — the starter block above is Part 1 of the lab.
← 5.2 Metadata