Ad – 728Γ—90
πŸ”§ Intermediate

Python CSV – Reading and Writing CSV Files

CSV (Comma-Separated Values) is the most common format for exchanging tabular data β€” spreadsheets, databases, reports. Python's built-in csv module provides robust reading and writing without any third-party dependencies.

⏱️ 18 min read🎯 IntermediateπŸ“… Updated 2026

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: 91

DictReader – 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 successfully
πŸ’‘
Tip

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 rows

Real-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