Reading CSV
Use csv.reader and csv.DictReader to read CSV files
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Reading with csv.reader
csv.reader reads each row as a list of strings — including the header row.
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)Reading with csv.DictReader
csv.DictReader reads each row as a dictionary. The keys come from the header row automatically. This makes accessing specific columns clear and readable.
with open("data.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"], row["score"])DictReader skips the header row — you get only the data rows.
Instructions
Read a student CSV file using both csv.reader and csv.DictReader.
- Import
csv. - Open
students.csvin read mode. Create acsv.readernamedreader. Write aforloop overreaderand callprint(row)inside. - Open
students.csvagain. Create acsv.DictReadernamedreader. Write aforloop overreaderand callprint(row["name"], row["score"])inside.
# students.csv contains: # name,grade,score # Alice,A,95 # Bob,B,82 # Charlie,A,91 # Step 1: Import csv # Step 2: Read students.csv with csv.reader and print each row # Step 3: Read students.csv with csv.DictReader and print name and score
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding