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.
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!
| Mode | Meaning | If File Already Exists | If File Doesn't Exist |
|---|---|---|---|
"r" | Read (default) | Reads from start | Raises FileNotFoundError |
"w" | Write | Erases old contents! | Creates new empty file |
"a" | Append | Adds to the end safely | Creates new empty file |
"x" | Exclusive create | Raises FileExistsError | Creates new file |
# 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!
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).
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]):
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
Quick Quiz: Module 6.2 — Files, pathlib & JSON
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.