20. CSV
Comma-separated values, or CSV, is a simple text format for tabular data. Python’s csv module helps you read and write rows safely without manually splitting strings.
20.1. Writing CSV
Use csv.writer when you want to write rows to a CSV file.
1import csv
2
3rows = [
4 ['name', 'score'],
5 ['Ava', 95],
6 ['Noah', 88],
7 ['Mia', 91],
8]
9
10with open('scores.csv', 'w', newline='') as f:
11 writer = csv.writer(f)
12 writer.writerows(rows)
20.2. Reading CSV
Use csv.reader to read rows back from a CSV file.
1import csv
2
3with open('scores.csv', newline='') as f:
4 reader = csv.reader(f)
5 for row in reader:
6 print(row)
20.3. Dictionary rows
When your data has named columns, DictReader and DictWriter are often easier to understand.
1import csv
2
3rows = [
4 {'name': 'Ava', 'score': 95},
5 {'name': 'Noah', 'score': 88},
6]
7
8with open('scores_dict.csv', 'w', newline='') as f:
9 writer = csv.DictWriter(f, fieldnames=['name', 'score'])
10 writer.writeheader()
11 writer.writerows(rows)
12
13with open('scores_dict.csv', newline='') as f:
14 reader = csv.DictReader(f)
15 for row in reader:
16 print(row['name'], row['score'])
20.4. Exercise
Write a CSV file for student scores with the columns name and score. Then read the file back and print only the students whose score is at least 90.
20.4.1. Solution
1import csv
2
3rows = [
4 {'name': 'Ava', 'score': 95},
5 {'name': 'Noah', 'score': 88},
6 {'name': 'Mia', 'score': 91},
7]
8
9with open('scores.csv', 'w', newline='') as f:
10 writer = csv.DictWriter(f, fieldnames=['name', 'score'])
11 writer.writeheader()
12 writer.writerows(rows)
13
14with open('scores.csv', newline='') as f:
15 reader = csv.DictReader(f)
16 for row in reader:
17 if int(row['score']) >= 90:
18 print(row['name'])