Reading CSV Files
csv.reader reads each row as a list of strings.
Python
import csv
# Example CSV (students.csv):
# name,grade,score
# Alice,A,95
# Bob,B,82
# Charlie,A,91
with open("students.csv", "r") as f:
reader = csv.reader(f)
header = next(reader) # Skip header row
print(f"Columns: {header}")
for row in reader:
print(f"{row[0]}: {row[2]}")βΆ Output
Columns: ['name', 'grade', 'score']
Alice: 95
Bob: 82
Charlie: 91DictReader β Rows as Dictionaries
csv.DictReader maps each row to a dict using the header row as keys.
Python
import csv
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['name']} scored {row['score']} (grade {row['grade']})")βΆ Output
Alice scored 95 (grade A)
Bob scored 82 (grade B)
Charlie scored 91 (grade A)Writing CSV Files
csv.writer writes lists as CSV rows.
Python
import csv
students = [
["name", "grade", "score"], # header
["Alice", "A", 95],
["Bob", "B", 82],
["Charlie", "A", 91]
]
with open("output.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(students)
print("CSV written successfully")βΆ Output
CSV written successfullyTip
Always pass newline="" when opening CSV files on Windows to prevent extra blank lines.
Ad β 336Γ280
DictWriter β Write from Dicts
Use DictWriter when your data is in dictionary form.
Python
import csv
rows = [
{"name": "Alice", "grade": "A", "score": 95},
{"name": "Bob", "grade": "B", "score": 82},
]
with open("output.csv", "w", newline="") as f:
fields = ["name", "grade", "score"]
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader() # Write column names
writer.writerows(rows) # Write all rowsReal-World: Analyse CSV Data
Compute statistics from a CSV without pandas.
Python
import csv
total, count = 0, 0
with open("students.csv", "r") as f:
for row in csv.DictReader(f):
total += int(row["score"])
count += 1
print(f"Average score: {total/count:.1f}")βΆ Output
Average score: 89.3