█
LastWrite
  • > Curriculum
  • > Pricing
  • > For Educators
  • > About
  • > Contact
Log InGet Started

Questions, concerns, bug reports, or suggestions? We read every message, write to us at [email protected].

More ways to reach us →
LastWrite

Structured computer science lessons for aspiring developers and security professionals.

[email protected]

(201) 785-7951

Mon–Fri, 9 AM–5 PM EST

Learn

  • Curriculum
  • Pricing

Company

  • About
  • For Educators & Schools
  • Contact Us

Legal

  • Terms of Service
  • Privacy Policy
© 2026 LastWrite. All rights reserved.
Curriculum/Programming Languages/Python (Professional)/File I/O and Working with Data
40 minIntermediate

File I/O and Working with Data

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.

Prerequisites:Error Handling

pathlib + open() done right

pathlib replaces os.path for new code.

python
from pathlib import Path
# Build paths
root = Path(__file__).parent
data_file = root / "data" / "users.csv"
# Check / create
data_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 all
data_file.write_text("hello")
# Iterate line by line (large files)
with data_file.open() as f:
for line in f:
process(line)
# List files
for py_file in root.rglob("*.py"):
print(py_file)

CSV + JSON

Standard library handles both.

python
import csv
from pathlib import Path
# CSV with header
with open("users.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["email"])
# Write CSV
rows = [{"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)
# JSON
import json
data = json.loads(Path("data.json").read_text())
Path("out.json").write_text(json.dumps(data, indent=2))

Encodings

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.

Common mistakes only experienced Python devs avoid

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).

Quick Check

Why prefer pathlib over os.path?

Pick the cleanest answer.

Sign in and purchase access to unlock this lesson.

Sign in to purchase
←Error Handling and Logging
Back to Python (Professional)
Python Standard Library Deep Dive→