The tempfile module creates temporary files and directories with secure names and portable APIs. Its context managers clean resources on exit, including when an exception interrupts processing.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory(prefix="relatorio-") as pasta:
destino = Path(pasta) / "resultado.txt"
destino.write_text("processamento concluído", encoding="utf-8")
print(destino.read_text(encoding="utf-8"))
## A pasta e seu conteúdo já foram removidos.
TemporaryDirectory yields a path and removes its tree when the with block ends. SpooledTemporaryFile keeps data in memory up to a threshold and then rolls over to disk. NamedTemporaryFile helps when another API needs a filename, but reopening behavior can vary by platform.
Practical guidance
Do not use mktemp(): it returns only a name and leaves a race before creation. Prefer high-level interfaces or mkstemp() when you need direct descriptor control and can guarantee cleanup. Temporary storage is not persistence, backup, or a home for long-lived secrets.
Pair it with pathlib for path operations. In tests, use pytest fixtures and monkeypatch to isolate filesystem behavior.
The official tempfile module documentation, accessed July 22, 2026, documents the API and its guarantees.