Codectionary / Developer documentation / Python

Temporary files and directories

Create short-lived working storage with automatic cleanup and explicit file lifetimes.

How it works

tempfile provides safely created temporary storage instead of requiring you to invent a predictable filename. High-level context managers close resources and normally clean them up when the block ends.

TemporaryDirectory supplies a directory path. TemporaryFile supplies an open file object. Examples here close files before directory cleanup and print stable contents rather than randomly generated paths.

Limitations and practical choices

Context-manager cleanup does not promise secure erasure or cleanup after every possible process or machine crash.

Keep resources inside their managed lifetime. Reopening a still-open named temporary file has platform-specific constraints, especially on Windows; these examples avoid that dependency.

Try it yourself

Write two reports into a temporary directory, read them while the context is active, then confirm the directory no longer exists.

Syntax

from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
    ...

Examples

Create an isolated report

Read a file during its temporary directory lifetime.

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
    report = Path(folder) / "report.txt"
    report.write_text("Ready", encoding="utf-8")
    print(report.read_text(encoding="utf-8"))
print(report.exists())
  1. The context creates a fresh directory. Path joins a filename within it, and the text methods open and close the file for each operation.
  2. Leaving the context removes the directory and its file. The Path object remains, but it no longer points to an existing file.
  3. Use isolated temporary directories for tests or intermediate exports rather than writing into a shared project folder.
  4. Expected output: Ready False

Use an unnamed working file

Rewind an open file before reading its contents.

from tempfile import TemporaryFile
with TemporaryFile(mode="w+t", encoding="utf-8") as file:
    file.write("alpha\nbeta\n")
    file.seek(0)
    print(file.read(), end="")
  1. w+t opens a readable and writable text file. Writing advances the cursor, so seek(0) moves back to the beginning.
  2. read then retrieves both lines. end="" avoids adding another newline because the stored text already ends with one.
  3. Use an open temporary file when an API accepts a file object and no reusable path is required.
  4. Expected output: alpha beta

Verify cleanup on an error

Confirm that an exception still exits the context manager.

from pathlib import Path
from tempfile import TemporaryDirectory
try:
    with TemporaryDirectory() as folder:
        location = Path(folder)
        raise ValueError("conversion failed")
except ValueError:
    print("Conversion failed")
print(location.exists())
  1. The exception leaves the with block before reaching the handler. TemporaryDirectory performs its normal cleanup during that exit.
  2. The final existence check demonstrates that this ordinary exception path did not leave the directory behind.
  3. Keep cleanup in a context manager so successful and failed processing paths share the same resource-lifetime rule.
  4. Expected output: Conversion failed False

Best practices

  • Context-manager cleanup does not promise secure erasure or cleanup after every possible process or machine crash.
  • Keep resources inside their managed lifetime. Reopening a still-open named temporary file has platform-specific constraints, especially on Windows; these examples avoid that dependency.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading