Batu Lab NotesPractical developer guides

Create a unique temporary work directory

By Batu · English technical notes

Also published in our Blogger archive.

Create a unique temporary work directory

A temporary work directory gives one operation a place for intermediate files without selecting a predictable shared name yourself. TemporaryDirectory() creates the directory, and its context-manager form arranges cleanup when the block ends. This example creates a work directory with a readable build- prefix, writes a tiny marker, and checks both the directory and marker before printing a stable status message.

The actual generated directory name intentionally never appears in stdout. It contains a random portion, so printing it would make the example nondeterministic. Instead, work.is_dir() confirms the directory exists while the context is active, and read_text() verifies that the controlled marker content is exactly ready followed by a newline. The two messages describe the observable stages without exposing a host-specific temporary path.

The context manager normally removes the directory and all its contents on exit, but cleanup can still report errors in circumstances such as permission problems or open handles. The assertions do not prove uniqueness across every possible environment, nor do they make files inside the directory private from every local actor. The tempfile module creates randomly named temporary directories using secure creation rules; TemporaryDirectory was added in Python 3.2. Details of cleanup, prefixes, and error behavior are in the official tempfile documentation.

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(prefix="build-") as name:
    work = Path(name)
    marker = work / "result.txt"
    marker.write_text("ready\n", encoding="utf-8")

    assert work.is_dir()
    assert marker.read_text(encoding="utf-8") == "ready\n"
    print("work directory ready")

print("cleanup requested")
work directory ready
cleanup requested

Sources