Python Intermediate - Lesson 02 - Working with CSV and JSON Data

Python Intermediate · Lesson 02

Working with CSV and JSON Data

Spreadsheets and web services often exchange information as CSV or JSON. Python’s built-in csv and json modules let you read and write both formats without installing extra packages.

By the end, you can: read CSV rows by header, write rows safely, load JSON into Python values, and save a structured summary as JSON.
File safety: opening a file in "w" mode replaces its contents. Practice with a copy or a dedicated test folder. The project creates a sample CSV only when one is missing and regenerates its JSON report each run.

1. Read a CSV file with headers

CSV stores rows and columns as text. csv.DictReader uses the first row as column names, then gives you each later row as a dictionary.

import csv

with open("sessions.csv", newline="", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        topic = row["topic"]
        minutes = int(row["minutes"])
        print(f"{topic}: {minutes} minutes")

CSV values are strings by default. Convert a numeric field with int() or float() before calculating with it.

2. Write rows to a CSV file

DictWriter maps dictionary keys to named columns. The newline="" option helps the CSV module manage line endings consistently.

import csv

fieldnames = ["topic", "minutes"]
rows = [
    {"topic": "lists", "minutes": 25},
    {"topic": "functions", "minutes": 30}
]

with open("sessions.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)

This example uses "w" mode, so it replaces an existing sessions.csv. Use it only when that is what you intend.

3. Load JSON from a file

JSON represents structured data. Objects become Python dictionaries, arrays become lists, and JSON numbers, strings, booleans, and null values become their Python equivalents.

import json

with open("summary.json", encoding="utf-8") as file:
    summary = json.load(file)

print(summary["total_minutes"])

Use json.load() to read from an open file. Use json.dump() to write Python data to an open file.

4. Save a Python dictionary as JSON

import json

summary = {
    "topic": "Python practice",
    "sessions": 2,
    "total_minutes": 55
}

with open("summary.json", "w", encoding="utf-8") as file:
    json.dump(summary, file, indent=2)

The indent=2 option makes the output easier for people to read. JSON is a text format, so you can open the saved file in a text editor.

Hands-on exercises

  1. Use csv.DictWriter to write two book rows with the columns title and pages.
  2. Load a JSON file into a Python value, then print its "name" field. Save a dictionary with a name and score to a new JSON file.
Show Solution & Common Mistakes

Exercise 1 — one possible solution

import csv

books = [
    {"title": "The Paper Bridge", "pages": 180},
    {"title": "Small Bright Ideas", "pages": 240}
]
columns = ["title", "pages"]

with open("books.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=columns)
    writer.writeheader()
    writer.writerows(books)

Exercise 2 — one possible solution

import json

with open("person.json", encoding="utf-8") as file:
    person = json.load(file)

print(person["name"])

result = {"name": "Avery", "score": 92}
with open("result.json", "w", encoding="utf-8") as file:
    json.dump(result, file, indent=2)

Common mistakes:

  • Forgetting that CSV values are strings and need conversion for math.
  • Leaving out newline="" when opening CSV files for writing.
  • Calling json.load() with a filename string instead of an open file. Use json.load(file).
  • Accidentally replacing an important file with "w" mode. Use a test filename while learning.

Quick quiz

Choose an answer, then select Check answer.

1. What does csv.DictReader use as keys?

2. Which function reads JSON from an open file?

3. What type does a CSV reader usually return for a field?

Mini-project: Study Session Report

Read study sessions from a CSV file, calculate a summary, and save that summary as JSON.

Requirements:

  • Use a folder named study_report.
  • If sessions.csv is missing, create a small sample file.
  • Read each session’s topic and minutes from the CSV.
  • Calculate the session count, total minutes, and average minutes.
  • Save the session data and calculations to summary.json.

Sample CSV data:

topic,minutes
lists,25
functions,30
files,20

Expected summary values:

session_count: 3
total_minutes: 75
average_minutes: 25.0

Hint: Use Path.exists() before making a sample CSV. Convert each minutes field with int(). The project replaces its generated JSON report on each run, but it does not replace an existing CSV.

Show Full Project Solution
import csv
import json
from pathlib import Path

folder = Path("study_report")
folder.mkdir(exist_ok=True)
csv_path = folder / "sessions.csv"
json_path = folder / "summary.json"

if not csv_path.exists():
    sample_rows = [
        {"topic": "lists", "minutes": 25},
        {"topic": "functions", "minutes": 30},
        {"topic": "files", "minutes": 20}
    ]
    with csv_path.open("w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=["topic", "minutes"])
        writer.writeheader()
        writer.writerows(sample_rows)

sessions = []
with csv_path.open(newline="", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        sessions.append({
            "topic": row["topic"],
            "minutes": int(row["minutes"])
        })

if not sessions:
    print("The CSV has no session rows yet.")
else:
    total_minutes = sum(session["minutes"] for session in sessions)
    summary = {
        "sessions": sessions,
        "session_count": len(sessions),
        "total_minutes": total_minutes,
        "average_minutes": total_minutes / len(sessions)
    }

    with json_path.open("w", encoding="utf-8") as file:
        json.dump(summary, file, indent=2)

    print(f"Saved report to {json_path}")
    print(json_path.read_text(encoding="utf-8"))

The CSV is created only when missing, so an existing session file is preserved. The JSON report is generated output and is replaced each time the program runs.

Key takeaways

  • Use csv.DictReader and DictWriter for rows with headers.
  • Convert CSV text fields before calculating with them.
  • Use json.load() to read and json.dump() to write JSON files.
  • Use a test folder and know whether write mode replaces an existing file.

Posts les plus consultés de ce blog

Python Programming Exercises with Solutions - Complete Beginner's Guide

Python Basics - Capstone - Study Sprint Tracker

Python Intermediate - Lesson 10 - Working with Excel Spreadsheets