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.

  1. Import csv.
  2. Open students.csv in read mode. Create a csv.reader named reader. Write a for loop over reader and call print(row) inside.
  3. Open students.csv again. Create a csv.DictReader named reader. Write a for loop over reader and call print(row["name"], row["score"]) inside.