Python
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="").
Exercise 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)).
Show example solution
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))
Test yourself
-
What does csv.reader yield for each row?
- A tuple
- A list
- A dictionary
- A string
Show answer
A list — You picked the wrong answer. Correct answer: a list. Each row's columns are list items.
-
Complete the csv.reader call
import csv
with open("members.csv", encoding="utf-8", newline="") as f:
reader = csv.____(f)
for row in reader:
print(row)
Show answer
import csv
with open("members.csv", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)
-
Match the CSV concepts
- csv.reader
- Reads rows
- row
- Single row data
- newline=""
- Line-ending setting
- import csv
- Module import
Next lesson: csv.writer