Warming up the neural circuits...
By the end of this chapter you will:
Programs that can't persist are toys. Real programs read config files, process CSV data, save results to disk, and log errors. File I/O is the plumbing that connects your code to the outside world.
# Read entire file
with open("data.txt", "r") as f:
content = f.read()
# Read lines
with open("data.txt") as f:
lines = f.readlines() # list of strings
# Read line by line (memory efficient)
with open("data.txt") as f:
for line in f:
print(line.strip())| Mode | Description |
|---|---|
'r' | Read (default) |
'w' | Write (overwrites!) |
'a' | Append |
'x' | Create (fails if exists) |
'b' | Binary (add to other modes) |
Key: Always use with — it closes the file automatically, even if an error occurs.
# Write string
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
# Write lines
lines = ["Line 1\n", "Line 2\n"
from pathlib import Path
# Build paths
data_dir = Path("data")
file_path = data_dir / "users.json"
# Windows: data\users.json
# Unix: data/users.json
# Check existence
print(file_path.exists
import json
# Read JSON from file
with open("config.json") as f:
config = json.load(f)
# Write JSON to file
data = {"name": "Alice", "age"
import csv
# Read CSV
with open("data.csv") as f:
reader = csv.reader(f)
for row in reader:
print(row) # ['Alice', '30', 'Engineer']
# Read as dicts
Open → Read/Write → Close
↑ ↑ ↑
with f.read() automatic
f.write()| Mistake | Why it's wrong | Fix |
|---|---|---|
open("file") without with | File handle leaks | Always use with open() |
open("file", "w") accidentally | Overwrites file! | Double-check mode |
path = "dir" + "/" + "file" | Not cross-platform | Use Path("dir") / "file" |
| CSV extra blank lines (Windows) | Missing newline="" | open("f.csv", "w", newline="") |
with open().{"name": "Alice", "age": 30}with open() better than f = open()?Beginner:
"What does with open() do?"
with open()is a context manager that automatically closes the file when the block exits, even if an error occurs. It prevents file handle leaks.
"What's the difference between json.load() and json.loads()?"
json.load(f)reads JSON from a file object.json.loads(s)parses a JSON string. Useloadfor files,loadsfor strings.
Senior:
"Why use pathlib instead of os.path?"
pathlib provides an object-oriented for paths. It's more readable (
Path("dir") / "file"vs), cross-platform, and has useful methods (exists, is_file, glob). It's the modern way to handle paths in Python.
with open("file") as f: — safe reading, automatic closepathlib.Path("dir") / "file" — cross-platform pathsjson.load(f) / json.dump(data, f) — JSON filescsv.reader(f) / csv.DictReader(f) — CSV fileswith to prevent file handle leaksI want to…
├── Read file → with open("f") as f: f.read()
├── Write file → with open("f", "w") as f: f.write(s)
├── Build path → Path("dir") / "file"
├── Read JSON → json.load(f)
├── Write JSON → json.dump(data, f, indent=2)
├── Read CSV → csv.DictReader(f)
└── Write CSV → csv.writer(f)Why use 'with open()' instead of 'f = open()'?
Warning: 'w' mode overwrites the file! Use 'a' to append.
| Operation | Code |
|---|---|
| Build path | Path("dir") / "file" |
| Check exists | path.exists() |
| Read text | path.read_text() |
| Write text | path.write_text(s) |
| List dir | path.iterdir() |
| Glob | path.glob("*.txt") |
Note: JSON keys must be strings. json.dump with indent=2 for readable output.
Key: Use newline="" when writing CSV on Windows to avoid extra blank lines.
"What's the difference between text mode and binary mode?"
Text mode (
'r','w') reads/writes strings with encoding (UTF-8 by default). Binary mode ('rb','wb') reads/writes bytes. Use binary for images, executables, and non-text data. Use text for CSV, JSON, and human-readable files.