Course Progress48%
🍎 Python Basics Topic 48 / 100
⏳ 7 min read

Working with CSV

Read and write tabular data — CSV is the universal format for spreadsheets and data exports.

"CSV is the simplest format for tabular data. Every spreadsheet can export it. Every language can read it. Python’s csv module makes it effortless."

— ShurAI

What is CSV?

CSV stands for Comma-Separated Values. It stores tabular data as plain text — each row is a line, each column is separated by a comma. Open any spreadsheet and choose “Save as CSV” to get one.

📄 students.csv — raw text inside the file
name,score,grade
Riya,92,A
Arjun,75,B
Sneha,88,A
Vikram,61,C
name
score
grade
Riya
92
A
Arjun
75
B
Sneha
88
A

Reading a CSV File

python
import csv

with open("students.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# [’name’, ’score’, ’grade’]
# [’Riya’, ’92’, ’A’]
# [’Arjun’, ’75’, ’B’]
# [’Sneha’, ’88’, ’A’]
# [’Vikram’, ’61’, ’C’]

DictReader — Each Row as a Dictionary

This is the better way. Instead of a list, each row is a dictionary where keys are the column headers — much more readable:

python
import csv

with open("students.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['name']:10} scored {row['score']} — Grade {row['grade']}")

# Riya       scored 92 — Grade A
# Arjun      scored 75 — Grade B
# Sneha      scored 88 — Grade A
# Vikram     scored 61 — Grade C

Writing a CSV File

python
import csv

data = [
    ["name",   "score", "grade"],   # header row
    ["Riya",   92,      "A"],
    ["Arjun",  75,      "B"],
    ["Sneha",  88,      "A"],
]

with open("results.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(data)

print("results.csv created!")
Always add newline="" when writing CSV

On Windows, opening a file without newline="" adds an extra blank line between every row in the CSV. Always include it when writing CSVs to keep the file clean on all operating systems.

DictWriter — Write Dicts as Rows

python
import csv

students = [
    {"name": "Riya",   "score": 92, "city": "Mumbai"},
    {"name": "Arjun",  "score": 75, "city": "Delhi"},
    {"name": "Sneha",  "score": 88, "city": "Pune"},
]

with open("students.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "score", "city"])
    writer.writeheader()    # writes the column header row
    writer.writerows(students)

"DictReader and DictWriter are almost always better than plain reader/writer. Column names in your code are far clearer than mystery index numbers like row[2]."

— ShurAI

🧠 Quiz — Q1

What does CSV stand for?

🧠 Quiz — Q2

What does csv.DictReader return for each row?

🧠 Quiz — Q3

Why must you add newline="" when opening a CSV for writing?

🧠 Quiz — Q4

What is the difference between csv.writer and csv.DictWriter?