Create a missing nested output directory
Also published in our Blogger archive.
An output path often contains several directory levels that may not exist on a clean run. The example starts with a missing exports/2026/09 path under a temporary directory. Calling destination.mkdir(parents=True, exist_ok=True) creates the missing parents and the destination directory in one request. The first assertion documents the fixture’s starting condition; the second verifies that the resulting destination is a directory.
The second mkdir call shows why exist_ok=True is useful for repeatable setup: it accepts the directory after it already exists. The official Path.mkdir documentation specifies that parents=True creates missing parents and that exist_ok=True suppresses the error only when the target is an existing directory. TemporaryDirectory makes the example self-contained, while the printed relative label keeps stdout deterministic.
Use Python 3.5+ for the parents and exist_ok behavior shown. This does not guarantee that directory creation will succeed: permissions, a conflicting regular file, invalid names, or concurrent filesystem changes can still cause exceptions. Nor does is_dir() prove who created the directory or that later writes will be permitted. Production code should decide which creation errors to report or recover from.
AI-assistance disclosure: this article was drafted with AI assistance and should be reviewed in the context of its application.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as raw_directory:
destination = Path(raw_directory) / "exports" / "2026" / "09"
assert not destination.exists()
destination.mkdir(parents=True, exist_ok=True)
assert destination.is_dir()
destination.mkdir(parents=True, exist_ok=True)
print("created: exports/2026/09")
created: exports/2026/09