Skip to content

Lesson 1 of 9 · 20m

Filesystem Work Without Footguns

pathlib, atomic writes, safe cleanup, symlink awareness, and the file-handling habits that keep automation from deleting the wrong thing.

Every ops engineer eventually writes the script that deletes the wrong directory. Mine ran at 03:10 because a variable was empty and rm -rf "$BACKUP_DIR/" interpreted that as /. Python gives you safer tools, but only if you treat paths as operating-system objects rather than strings to concatenate.

Use pathlib, not string paths

from pathlib import Path

root = Path('/var/backups/app')
archive = root / '2026-11' / 'database.sql.gz'
archive.parent.mkdir(parents=True, exist_ok=True)

pathlib.Path makes joining and inspecting paths explicit. It does not make untrusted input safe — Path('/tmp') / user_input still escapes when user_input is absolute — but it removes separator and quoting mistakes. Learn the small core: is_file(), is_dir(), iterdir(), rglob('*.log'), stat().st_size, read_text(), and write_text().

Writes should be atomic

Half-written files are worse than missing files. Write beside the destination, flush, then rename:

import os
import tempfile

def write_atomic(path: Path, data: str) -> None:
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name + '.')
    with os.fdopen(fd, 'w', encoding='utf-8') as f:
        f.write(data)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)

os.replace is atomic on POSIX when source and destination are on the same filesystem. That is why the temporary file belongs in the destination directory, not /tmp. Production versions should also remove the temporary file in a finally block after failures.

Deletes need proof

Never recursively delete a path you have not validated:

def remove_tree(path: Path, expected_root: Path) -> None:
    resolved = path.resolve()
    root = expected_root.resolve()
    if resolved == root or root not in resolved.parents:
        raise ValueError(f'refusing to delete outside {root}: {resolved}')
    shutil.rmtree(resolved)

resolve() follows symlinks. That matters: a symlink inside your work directory can point outside it, and recursive deletion tools have historically handled symlink races poorly.

Streaming beats reading everything

Ops files grow. Iterate over file objects instead of calling .read() on logs, dumps, or artifacts that might become 40 GB. Python file objects are iterators line by line; use them.

Field notes

  • Path.exists() plus an operation is a time-of-check/time-of-use race; catch FileNotFoundError where practical.
  • os.replace overwrites atomically; Path.rename may fail across filesystems.
  • Normalize encodings deliberately. Production filenames are bytes; Python hides that until it does not.
  • Never pass operator-controlled path fragments into deletion logic without resolving and boundary-checking them.

Was this lesson helpful?

Sign in to rate