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())- The context creates a fresh directory. Path joins a filename within it, and the text methods open and close the file for each operation.
- Leaving the context removes the directory and its file. The Path object remains, but it no longer points to an existing file.
- Use isolated temporary directories for tests or intermediate exports rather than writing into a shared project folder.
- 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="")- w+t opens a readable and writable text file. Writing advances the cursor, so seek(0) moves back to the beginning.
- read then retrieves both lines. end="" avoids adding another newline because the stored text already ends with one.
- Use an open temporary file when an API accepts a file object and no reusable path is required.
- 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())- The exception leaves the with block before reaching the handler. TemporaryDirectory performs its normal cleanup during that exit.
- The final existence check demonstrates that this ordinary exception path did not leave the directory behind.
- Keep cleanup in a context manager so successful and failed processing paths share the same resource-lifetime rule.
- 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