Use Cleanup-Safe Temporary Resources
Core idea
TemporaryDirectory creates an isolated directory and removes its contents on normal context exit. TemporaryFile offers a file object without requiring a persistent name. NamedTemporaryFile has a visible name, but reopening and deletion rules depend on platform and options.
from pathlib import Pathfrom tempfile import TemporaryDirectorywith TemporaryDirectory() as folder: p = Path(folder) / "scratch" p.touch() print(p.exists())print(p.exists())The scratch file disappears with the directory.
Use an anonymous working file
from tempfile import TemporaryFilewith TemporaryFile(mode="w+b") as f: f.write(b"ABC") f.seek(0) print(f.read())print(f.closed)Seek returns to the start; context exit closes the file.
Common mistake
Do not invent a predictable name in a shared temporary folder. Use tempfile constructors. Abrupt termination and cleanup errors can leave files behind.
Practice
Create a temporary directory, write a report, raise a controlled ValueError inside with and check that the directory is removed after catching it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Temporary resource lifetime
Check your understanding of temporary files.
What is printed?
from tempfile import TemporaryFilewith TemporaryFile() as f: print(f.closed)print(f.closed)What is printed?
from tempfile import TemporaryDirectoryfrom pathlib import Pathwith TemporaryDirectory() as d: p = Path(d)print(p.exists())Which low-level API requires manual cleanup?
Why avoid assuming a named temporary file can be reopened while open?