TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Files and Paths with pathlib

Files and Paths with pathlib

Half of all automation is file work: find the logs older than seven days, render a config from a template, compare two directories, write a report where a web server can pick it up. pathlib (paths as objects), shutil (copy, move, archive), tempfile and os.replace cover all of it without a single shell command. Pyodide has an in-memory file system, so these examples really create, read and delete files in your browser.

Paths as objects

python · try it yourself
from pathlib import Path

base = Path("/srv/app")
conf = base / "config" / "app.yaml"           # join with /
print(conf)
print("name:", conf.name, "| stem:", conf.stem, "| suffix:", conf.suffix)
print("parent:", conf.parent, "| parts:", conf.parts)
print("with_suffix:", conf.with_suffix(".json"))
print("relative_to:", conf.relative_to(base))
print("is_relative_to /etc:", conf.is_relative_to("/etc"))
print("resolve '..':", (base / "releases" / ".." / "current").resolve())
/srv/app/config/app.yaml
name: app.yaml | stem: app | suffix: .yaml
parent: /srv/app/config | parts: ('/', 'srv', 'app', 'config', 'app.yaml')
with_suffix: /srv/app/config/app.json
relative_to: config/app.yaml
is_relative_to /etc: False
resolve '..': /srv/app/current

/ joins path parts without worrying about separators, and the attributes replace basename, dirname and ${f%.*} tricks. resolve() makes a path absolute and removes .. (following symlinks on a real disk), which is what you check before trusting a path that came from input: path.resolve().is_relative_to(allowed_root) stops ../../etc/passwd.

Creating, finding and reading files

python · try it yourself
from pathlib import Path
import os

root = Path("demo-logs")
for day, size in [("2026-01-10", 300), ("2026-01-12", 1200), ("2026-01-15", 50)]:
    for svc in ("api", "web"):
        d = root / svc
        d.mkdir(parents=True, exist_ok=True)               # mkdir -p
        (d / f"{svc}-{day}.log").write_text("x" * size)
(root / "api" / "README.txt").write_text("not a log\n")

logs = sorted(root.rglob("*.log"))                          # recursive glob
print(len(logs), "log files")
for p in logs:
    print(f"  {p.as_posix():32} {p.stat().st_size:>5} bytes")

big = [p.name for p in logs if p.stat().st_size > 1000]
print("over 1000 bytes:", big)
older = [p.name for p in logs if p.stem.split("-", 1)[1] < "2026-01-12"]
print("dated before 2026-01-12:", older)
print("total:", sum(p.stat().st_size for p in logs), "bytes")
6 log files
  demo-logs/api/api-2026-01-10.log   300 bytes
  demo-logs/api/api-2026-01-12.log  1200 bytes
  demo-logs/api/api-2026-01-15.log    50 bytes
  demo-logs/web/web-2026-01-10.log   300 bytes
  demo-logs/web/web-2026-01-12.log  1200 bytes
  demo-logs/web/web-2026-01-15.log    50 bytes
over 1000 bytes: ['api-2026-01-12.log', 'web-2026-01-12.log']
dated before 2026-01-12: ['api-2026-01-10.log', 'web-2026-01-10.log']
total: 3100 bytes
  • mkdir(parents=True, exist_ok=True) is the idempotent mkdir -p.
  • glob("*.log") searches one directory, rglob("*.log") the whole tree. Sort the results: directory order is not guaranteed.
  • read_text()/write_text() handle small files in one call. For large files iterate over an open file (for line in f:) so you never hold it all in memory.

On a real server you would compare modification times (p.stat().st_mtime against time.time() - 7 * 86400); this example uses the date in the file name so its output is the same on every run.

Writing files atomically

As in the Bash lesson, a file that other programs read must never be seen half-written. Write to a temporary file in the same directory, flush it to disk, then os.replace it over the target, which is an atomic rename on POSIX systems:

python · try it yourself
import json
import os
import tempfile
from pathlib import Path

def write_atomic(path: Path, text: str, mode: int = 0o644) -> None:
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())          # make sure the bytes are on disk before the rename
        os.chmod(tmp, mode)
        os.replace(tmp, path)             # atomic: readers see the old or the new file
    except BaseException:
        os.unlink(tmp)                    # never leave the temporary file behind
        raise

out = Path("status")
out.mkdir(exist_ok=True)
target = out / "health.json"
write_atomic(target, json.dumps({"healthy": 3, "down": 0}) + "\n")
print(target.read_text(), end="")

try:
    write_atomic(target, None)            # a bug: write() fails after the temporary file exists
except TypeError as e:
    print("failed:", e)
print(target.read_text(), end="")
print("files in status/:", sorted(p.name for p in out.iterdir()))
{"healthy": 3, "down": 0}
failed: write() argument must be str, not None
{"healthy": 3, "down": 0}
files in status/: ['health.json']

tempfile.mkstemp creates the file with a random name and private permissions (like mktemp), and the except BaseException branch removes it on any failure, even Ctrl+C. The failed write left the old content intact and no temporary file behind.

Copying, moving and archiving

shutil covers the rest of cp, mv, rm -r and tar:

python · try it yourself
import hashlib
import shutil
from pathlib import Path

src = Path("site")
(src / "css").mkdir(parents=True, exist_ok=True)
(src / "index.html").write_text("<h1>shop</h1>\n")
(src / "css" / "main.css").write_text("h1 { color: teal }\n")
(src / "debug.log").write_text("noise\n")

dest = Path("release-1.4.2")
shutil.rmtree(dest, ignore_errors=True)                       # rm -rf
shutil.copytree(src, dest, ignore=shutil.ignore_patterns("*.log"))
print("copied:", sorted(p.relative_to(dest).as_posix() for p in dest.rglob("*") if p.is_file()))

archive = shutil.make_archive("release-1.4.2", "gztar", root_dir=".", base_dir="release-1.4.2")
print("archive:", Path(archive).name)

def sha256(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):         # constant memory, any file size
            h.update(chunk)
    return h.hexdigest()

print("index.html sha256:", sha256(dest / "index.html")[:16], "...")
print("same as source:", sha256(dest / "index.html") == sha256(src / "index.html"))
copied: ['css/main.css', 'index.html']
archive: release-1.4.2.tar.gz
index.html sha256: 783652ab6a6189ef ...
same as source: True

copytree with ignore_patterns replaces rsync --exclude for simple cases; make_archive builds a .tar.gz (the archive's own checksum is not printed because gzip stores a timestamp in it). Hashing in fixed-size chunks works for files of any size.

Test yourself

What is the pathlib equivalent of mkdir -p logs/api?

  1. Path("logs/api").mkdir()
  2. Path("logs/api").mkdir(parents=True, exist_ok=True)
  3. os.mkdir("logs/api")
  4. Path("logs").touch()

Why does write_atomic create its temporary file in the target's directory?

  1. For tidiness
  2. os.replace is only an atomic rename within one file system
  3. tempfile cannot write to /tmp
  4. To inherit the target's permissions

How do you check that a path from user input stays inside /srv/app?

  1. '/srv/app' in str(p)
  2. p.resolve().is_relative_to('/srv/app')
  3. p.exists()
  4. p.name.startswith('srv')