Python - Files & I/O
Overview
Estimated time: 35–45 minutes
Open, read, and write files safely with context managers. Handle encodings correctly and use json/csv for simple data formats.
Learning Objectives
- Use
with open(...)
to manage file resources. - Set encoding explicitly for text files (UTF-8).
- Read and write JSON/CSV with the standard library.
Prerequisites
Text files
from pathlib import Path
p = Path("hello.txt")
with p.open("w", encoding="utf-8") as f:
f.write("Hello, file!\n")
with p.open("r", encoding="utf-8") as f:
content = f.read()
print(content)
Expected Output:
Hello, file!
JSON
import json
obj = {"name": "Ann", "age": 30}
with open("person.json", "w", encoding="utf-8") as f:
json.dump(obj, f)
with open("person.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data["name"]) # Ann
CSV
import csv
rows = [("name", "age"), ("Ann", 30), ("Ben", 25)]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(rows)
with open("people.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Common Pitfalls
- Not specifying encoding; default may vary by OS.
- Forgetting newline="" when writing CSV on Windows, causing blank lines.
Checks for Understanding
- Why use
with
when opening files? - How do you write a dict to a JSON file?
Show answers
- It ensures the file is closed even if an error occurs.
json.dump(obj, f)
Exercises
- Write a list of dicts to JSON and read it back, printing one field from each.
- Append a new row to an existing CSV file.