File I/O gives your programs persistence — the ability to save data to disk and reload it later — transforming throwaway scripts into applications that remember.
The File I/O Lifecycle
Step
What Happens
Python Code
Open
Establish a connection to a file
open("data.txt", "r")
Read or Write
Transfer data between program and disk
f.read(), f.write()
Close
Release the connection
Automatic with with
File Modes at a Glance
Mode
Purpose
Creates file?
Erases content?
"r"
Read
No (errors)
N/A
"w"
Write
Yes
Yes
"a"
Append
Yes
No
"x"
Exclusive create
Yes (errors if exists)
N/A
Reading Methods Compared
Method
Returns
Loads into memory?
Best for
f.read()
Single string
Entire file
Small files
f.readline()
One line (string)
One line
Peeking at headers
f.readlines()
List of strings
Entire file
When you need indexing
for line in f:
One line per iteration
One line at a time
Large files
The Golden Rule: Always Use with
# YES — file is always closed, even on errors
with open("data.txt", "r") as f:
content = f.read()
# NO — if an error occurs before close(), the file leaks
f = open("data.txt", "r")
content = f.read()
f.close()
CSV vs. JSON: When to Use Each
Criterion
CSV
JSON
Data shape
Flat table (rows & columns)
Nested/hierarchical
Type preservation
Everything is a string
Numbers, booleans, null preserved
Spreadsheet-friendly
Yes
No
API standard
Rare
Dominant
Nesting support
No
Yes
Best for
Spreadsheet data, bulk tabular data
Config files, API data, complex records
Essential Patterns
Read a file safely
from pathlib import Path
path = Path("data.txt")
if path.exists():
content = path.read_text(encoding="utf-8")
Process a CSV
import csv
with open("data.csv", "r", newline="") as f:
for row in csv.DictReader(f):
print(row["column_name"])
Save and load JSON
import json
# Save
with open("data.json", "w") as f:
json.dump(my_data, f, indent=2)
# Load
with open("data.json", "r") as f:
my_data = json.load(f)
Check file permissions, don't write to system dirs
UnicodeDecodeError
Wrong encoding assumption
Specify encoding="utf-8" or try "latin-1"
Empty file after "w"
Opened in write mode accidentally
Use "a" for append, or read before overwriting
Threshold Concept: Persistence
Programs without file I/O are like conversations — once they end, the information is gone. Programs with file I/O are like notebooks — they record information that survives beyond the current session. Every useful application you've ever used relies on this principle.
What's Next
Chapter 11: Error Handling — learn to catch and handle exceptions so your file I/O code (and everything else) is resilient to unexpected inputs, missing files, and corrupted data.