Lesson 6 of 40
Foundations
Beginner
โฑ 25 min
File I/O, Paths & JSON
Read and write text, CSV, and JSON files using pathlib, the modern context manager pattern, and Python's built-in json module.
Part 1: Reading & Writing Files
# Modern: pathlib.Path (preferred over os.path)
from pathlib import Path
p = Path("data/output.txt")
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("Hello, file!")
content = p.read_text()
# Context manager (safe, auto-closes)
with open("log.txt", "a", encoding="utf-8") as f:
f.write("New line ")
from pathlib import Path
p = Path("data/output.txt")
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("Hello, file!")
content = p.read_text()
# Context manager (safe, auto-closes)
with open("log.txt", "a", encoding="utf-8") as f:
f.write("New line ")
Part 2: JSON Serialization
import json
data = {"name":"Alice","scores":[95,87,92]}
# Serialize to string
json_str = json.dumps(data, indent=2)
# Write to file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Load from file
with open("data.json") as f:
loaded = json.load(f)
data = {"name":"Alice","scores":[95,87,92]}
# Serialize to string
json_str = json.dumps(data, indent=2)
# Write to file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Load from file
with open("data.json") as f:
loaded = json.load(f)
Part 3: CSV Reading & Writing
import csv
# Write CSV
with open("users.csv","w",newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name","age"])
writer.writeheader()
writer.writerow({"name":"Alice","age":30})
# Read CSV
with open("users.csv") as f:
for row in csv.DictReader(f):
print(row["name"])
# Write CSV
with open("users.csv","w",newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name","age"])
writer.writeheader()
writer.writerow({"name":"Alice","age":30})
# Read CSV
with open("users.csv") as f:
for row in csv.DictReader(f):
print(row["name"])
Part 4: pathlib Path Operations
from pathlib import Path
p = Path("reports/q3/sales.csv")
p.stem # "sales"
p.suffix # ".csv"
p.parent # Path("reports/q3")
p.exists() # True/False
# Glob โ find files by pattern
for csv_file in Path("data").rglob("*.csv"):
print(csv_file)
p = Path("reports/q3/sales.csv")
p.stem # "sales"
p.suffix # ".csv"
p.parent # Path("reports/q3")
p.exists() # True/False
# Glob โ find files by pattern
for csv_file in Path("data").rglob("*.csv"):
print(csv_file)
๐ Want the complete guide with projects?
Get the book โ