DCubes
Python module

Lesson 7

Paths and text files

Use pathlib to build paths, read and write text, and keep a clean lab layout.

beginner30 minRun on your machine

What you will be able to do

  • Build paths with pathlib.Path
  • Read and write UTF-8 text files
  • Organize lab input and output folders

Why this matters for data work

Jobs are path contracts: read data/raw/..., write data/out/.... pathlib beats string concatenation across Linux and Windows. Encodings matter the first time you meet a non-UTF-8 export.

Concepts

Path — object for a filesystem path: Path("data") / "raw" / "file.txt".

read_text / write_text — whole-file helpers for small files (labs and configs).

open — line-by-line or large files: with path.open() as f:.

mkdir(parents=True, exist_ok=True) — create lab directories safely.

encoding=“utf-8” — be explicit when you care.

Practice on your machine

cd ~/dcubes/python-lab
source .venv/bin/activate
cat > paths_lab.py << 'EOF'
from pathlib import Path

root = Path(__file__).resolve().parent
raw = root / "data" / "raw"
out = root / "data" / "out"
raw.mkdir(parents=True, exist_ok=True)
out.mkdir(parents=True, exist_ok=True)

sample = raw / "note.txt"
sample.write_text("first line\nsecond line\n", encoding="utf-8")

text = sample.read_text(encoding="utf-8")
print(text.strip())
print("lines", len(text.splitlines()))

dest = out / "note-copy.txt"
dest.write_text(text.upper(), encoding="utf-8")
print("wrote", dest)
EOF
python paths_lab.py
ls data/raw data/out
first line
second line
lines 2
wrote .../data/out/note-copy.txt

What you should see

  • data/raw and data/out under the lab.
  • Original and uppercase copy on disk.

Common mistakes

  • Hard-coded /Users/you/... — break on the next machine. Use paths relative to the script or cwd.
  • Forgetting encoding on non-ASCII data.
  • Writing into the repo root instead of data/out.

Next

CSV and JSON