After this lesson, you will be able to: Read and write files with pathlib, parse CSV and JSON, and work with data idiomatically.
Most Python scripts boil down to: read file → transform → write file. Master the patterns.
pathlib replaces os.path for new code.
from pathlib import Path# Build pathsroot = Path(__file__).parentdata_file = root / "data" / "users.csv"# Check / createdata_file.parent.mkdir(parents=True, exist_ok=True)data_file.exists()data_file.is_file()# Read all (small files)text = data_file.read_text()binary = data_file.read_bytes()# Write alldata_file.write_text("hello")# Iterate line by line (large files)with data_file.open() as f:for line in f:process(line)# List filesfor py_file in root.rglob("*.py"):print(py_file)
Standard library handles both.
import csvfrom pathlib import Path# CSV with headerwith open("users.csv") as f:reader = csv.DictReader(f)for row in reader:print(row["email"])# Write CSVrows = [{"name": "A", "age": 30}, {"name": "B", "age": 25}]with open("out.csv", "w", newline="") as f:writer = csv.DictWriter(f, fieldnames=["name", "age"])writer.writeheader()writer.writerows(rows)# JSONimport jsondata = json.loads(Path("data.json").read_text())Path("out.json").write_text(json.dumps(data, indent=2))
Files default to system encoding (often UTF-8 on macOS/Linux, sometimes cp1252 on Windows). Always specify: `open(path, encoding="utf-8")`. Mismatched encodings = mojibake (’ instead of '). JSON is always UTF-8.
Using `os.path.join` in new code. pathlib is cleaner. Forgetting `encoding="utf-8"`. Reading huge files into memory with .read(). Iterate line-by-line. Forgetting `newline=""` on CSV writer (causes blank rows on Windows).
Pick the cleanest answer.
Sign in and purchase access to unlock this lesson.