CSV stands for Comma-Separated Values. It stores a two-dimensional table as plain text: one record per row, one field per column, and usually a header in the first row.
Start with a small score table
This lesson uses a three-column table. Every record has the same fields, so rows map naturally to Python lists or dictionaries.
| Name | Python | Math |
|---|---|---|
| Alice | 92 | 85 |
| Bob | 78 | 90 |
| Mia | 88 | 95 |
Name,Python,Math
Alice,92,85
Bob,78,90
Mia,88,95KNOWLEDGE QUIZ
Write with csv.writer
Do not manually join fields with commas. csv.writer follows CSV quoting rules. writerow() writes one row; writerows() writes many. Use newline="" so the csv module manages line endings.
import csv
rows = [
["Name", "Python", "Math"],
["Alice", 92, 85],
["Bob", 78, 90],
["Mia", 88, 95]
]
with open("scores.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)KNOWLEDGE QUIZ
Read by position with csv.reader
csv.reader produces a list of strings for each row. The first row is the header, which can be consumed with next(reader). Later rows use positional indexes: row[0] is the name and row[1] is the Python score. CSV is text, so scores still need conversion to integers before arithmetic.
import csv
with open("scores.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
header = next(reader)
for row in reader:
python_score = int(row[1])
math_score = int(row[2])
average = (python_score + math_score) / 2
print(row[0], "%.1f" % average)Alice 88.5
Bob 84.0
Mia 91.5KNOWLEDGE QUIZ
Read, calculate, then write a report
A clear CSV program has three stages: read and convert types with csv.reader, calculate new values, then write a result with a header using csv.writer.
1 · Read csv.reader
2 · Transformint + average
3 · Write csv.writer
import csv
report = [["Name", "Average"]]
with open("scores.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
average = (int(row[1]) + int(row[2])) / 2
report.append([row[0], "%.1f" % average])
with open("report.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(report)Name,Average
Alice,88.5
Bob,84.0
Mia,91.5Create and read a contacts CSV
- Use csv.writer to create contacts.csv.
- Write the Name, Phone, Email header and three concrete contacts.
- Read it back with csv.reader and skip the header with next(reader).
- Print “name → email domain”, such as Alice → example.com.
Summarize product revenue
- Create sales.csv with Product, Quantity, and UnitPrice.
- Write Apple 3×2.5, Notebook 2×12, Apple 4×2.5, and Pen 5×3.
- Read with csv.reader and accumulate Quantity × UnitPrice by product.
- Use csv.writer to create sales_summary.csv with a Product and Revenue header, formatted to two decimals.