CodeBlanks Logo Icon CodeBlanks

csv.reader

Learn to read CSV with csv.reader.

Reading rows with csv.reader

CSV (comma-separated values) files store tabular data as plain text. Python's csv module makes reading them easy. You import the module with import csv.

To read, you open the file, then create a reader object with csv.reader(f). Looping over this object gives each row as a list; columns are list items. When opening the file you also pass newline="" to prevent double-processing of line endings.

Why is the newline parameter important?

The newline="" parameter when opening the file is critical for the CSV module. It disables Python's automatic line-ending conversion so the csv module handles line endings with its own rules.

Without it, on Windows line endings become \r\n and some rows may come back empty. encoding="utf-8" also keeps Turkish characters safe. That's why CSV files always use open("f.csv", encoding="utf-8", newline="").

Practice Read a CSV file and print the row count

Start with import csv. Then in a with open("members.csv", "w", encoding="utf-8", newline="") as f: block write three lines with f.write("name,age\n"), f.write("Ayşe,30\n") and f.write("Ali,25\n"). Then in a with open("members.csv", "r", encoding="utf-8", newline="") as f: block, do reader = csv.reader(f) and rows = list(reader). Finally print the count with print(len(rows)).

Starter code

main.py
import csv

# Write three rows to a CSV file
# Read the same file with csv.reader and print the row count

Sample solution

main.py
import csv

# Write three rows to a CSV file
with open("members.csv", "w", encoding="utf-8", newline="") as f:
    f.write("name,age\n")
    f.write("Ayşe,30\n")
    f.write("Ali,25\n")
# Read the same file with csv.reader and print the row count
with open("members.csv", "r", encoding="utf-8", newline="") as f:
    reader = csv.reader(f)
    rows = list(reader)
    print(len(rows))

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does csv.reader yield for each row?

  • A tuple
  • A list Correct answer
  • A dictionary
  • A string

Explanation: You picked the wrong answer. Correct answer: a list. Each row's columns are list items.

2 Complete the csv.reader call

Question
import csv

with open("members.csv", encoding="utf-8", newline="") as f:
    reader = csv.____(f)
    for row in reader:
        print(row)
Answer
import csv

with open("members.csv", encoding="utf-8", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Explanation: csv.reader(f) returns a reader object.

3 Match the CSV concepts

Term Meaning
csv.reader Reads rows
row Single row data
newline="" Line-ending setting
import csv Module import

All lessons in Intermediate