Python · Module 06: Modules, Files & Error HandlingTutorial 17 of 30
All Tutorials·~1.5 hrs

6.2 File Handling (with open), pathlib, JSON & CSV

Save and load real data from disk! Master safe file handling with context managers, modern cross-platform paths with pathlib, and parsing JSON & CSV files.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Safe File I/O: Always Use with open(...)

Think of opening a file on disk like borrowing a library book: if your program crashes before returning (closing) the file, you leak OS file handles and risk corrupted writes.

Python's with statement (Context Manager) guarantees the file is closed automatically the instant the indented block finishes — even if an error occurs inside!

Visual: Why `with open(...) as f:` Never Leaks File Handles (Even If an Error Happens!)
1. Enter `with`Opens file on disk__enter__()2. Run Indented BlockRead / Write JSON/CSVf.read() / json.load(f)3. Exit `with`AUTO-CLOSES file ✓__exit__() even on crash!→→Always use `with open(...)` instead of manual `f = open(); f.close()`.
ModeMeaningIf File Already ExistsIf File Doesn't Exist
"r"Read (default)Reads from startRaises FileNotFoundError
"w"WriteErases old contents!Creates new empty file
"a"AppendAdds to the end safelyCreates new empty file
"x"Exclusive createRaises FileExistsErrorCreates new file
PYTHON
# Writing text safely (always specify encoding="utf-8"!)
with open("notes.txt", mode="w", encoding="utf-8") as f:
    f.write("Line 1: Learn Python\n")
    f.write("Line 2: Build projects\n")

# Reading line-by-line (memory-efficient even for huge files!)
with open("notes.txt", mode="r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

2. Modern Paths with pathlib (No More Windows \ vs. Mac / Bugs!)

Never glue folder paths with strings like "data\\" + filename. Use Python's built-in pathlib.Path — the / operator automatically builds valid paths on Windows, macOS, and Linux!

PYTHON
from pathlib import Path

data_dir = Path("data")
data_dir.mkdir(exist_ok=True)             # Creates folder if missing

file_path = data_dir / "settings.txt"     # Clean, cross-platform!
file_path.write_text("theme=dark\n", encoding="utf-8")

if file_path.exists():
    print(file_path.read_text(encoding="utf-8"))

3. Working with JSON (The Language of APIs & Configs)

Python's built-in json module converts effortlessly between JSON files and Python dicts/lists:

  • json.dump(data, f, indent=2) → writes Python dict/list to a file (dumps = to string).
  • json.load(f) → reads JSON file back into a Python dict/list (loads = from string).
PYTHON
import json

profile = {"name": "Aarav", "skills": ["Python", "SQL"], "active": True}

# Save to disk
with open("profile.json", "w", encoding="utf-8") as f:
    json.dump(profile, f, indent=2)

# Load back into a Python dict
with open("profile.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded["skills"])   # ['Python', 'SQL']

4. Working with CSV Spreadsheets (csv.DictReader)

Use csv.DictReader so every row becomes a clean dictionary keyed by column header (instead of cryptic row[0], row[2]):

PYTHON
import csv

with open("sales.csv", "r", encoding="utf-8", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["item"], "->", float(row["price"]))

5. Interactive Trace: Reading, Updating & Saving JSON

Tracing a Persistent JSON Config Update
Interactive Line-by-Line Execution Trace · Step 1 of 5
1import json
2→raw = '{"visits": 4}'
3data = json.loads(raw)
4data["visits"] += 1
5saved = json.dumps(data)
6print(saved)
Variables in Memory
raw'{"visits": 4}'str
Console Output
(nothing printed yet)
What just happened: JSON stored on disk or sent over HTTP is plain text (str).

Quick Quiz: Module 6.2 — Files, pathlib & JSON

Q1.What happens if you open an existing file with `open("notes.txt", "w")`?
Q2.What is the difference between `json.load()` and `json.loads()`?
Q3.Why is `with open(...) as f:` preferred over `f = open(...)`?

Keep Exploring: Related Lessons & Tools

All Courses →