Recipe 10.7 · Python
Temp Files That Clean Up After Themselves
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Code creates temporary files for conversions, downloads and report generation, and forgets them. On one manufacturing client's report server, the temp folder held more than a million files and had silently pushed the system drive to its last few megabytes. Path.GetTempFileName adds its own trap: on Windows it fails once the temp folder holds 65,535 files with its naming pattern.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Write PDF bytes to a temp file for conversion and never delete it
Source: ImproveCode, Chapter 10, Recipe 10.7 "Temp Files That Clean Up After Themselves"
Section: The way it's often written
Book page: 225 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Path.GetTempFileName -> tempfile.mkstemp (creates the file, like the .NET call).
"""
import os
import tempfile
from collections.abc import Callable
def convert(pdf_bytes: bytes, output: str,
convert_to_tiff: Callable[[str, str], None]) -> None:
fd, tmp = tempfile.mkstemp()
os.close(fd)
with open(tmp, "wb") as f:
f.write(pdf_bytes)
convert_to_tiff(tmp, output)
# tmp is never deleted
The improved recipe
Wrap temp files and folders in disposable types so using deletes them, put them under one application-specific folder, and sweep that folder for leftovers at startup.
A usage snippet:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Self-deleting temp files and folders, delete-on-close scratch streams, sweeper
Source: ImproveCode, Chapter 10, Recipe 10.7 "Temp Files That Clean Up After Themselves"
Section: The improved recipe
Book page: 225-227 -- original C# listing
Converted from C# to Python.
IDisposable -> context managers; FileOptions.DeleteOnClose ->
tempfile.TemporaryFile (deleted on close by the OS/runtime);
Directory.CreateTempSubdirectory -> tempfile.mkdtemp.
"""
from __future__ import annotations
import os
import secrets
import shutil
import tempfile
import time
from datetime import timedelta
from types import TracebackType
from typing import IO
_ROOT = os.path.join(tempfile.gettempdir(), "ImproveCode")
class TempFile:
def __init__(self, path: str) -> None:
self.full_path = path
@staticmethod
def create(extension: str = ".tmp") -> "TempFile":
os.makedirs(_ROOT, exist_ok=True)
name = secrets.token_hex(6) # Path.GetRandomFileName
path = os.path.join(_ROOT, name + extension)
with open(path, "xb"):
pass
return TempFile(path)
@staticmethod
def open_scratch_stream() -> IO[bytes]:
os.makedirs(_ROOT, exist_ok=True)
return tempfile.TemporaryFile(mode="w+b", buffering=81920, dir=_ROOT)
@staticmethod
def sweep_older_than(age: timedelta) -> int:
if not os.path.isdir(_ROOT):
return 0
deleted = 0
cutoff = time.time() - age.total_seconds()
for entry in os.scandir(_ROOT):
if entry.stat(follow_symlinks=False).st_mtime >= cutoff:
continue
try:
if entry.is_dir(follow_symlinks=False):
shutil.rmtree(entry.path)
else:
os.remove(entry.path)
deleted += 1
except OSError:
# In use by a running job; the next sweep retries.
pass
return deleted
def close(self) -> None:
try:
os.remove(self.full_path)
except FileNotFoundError:
pass
except OSError:
# Still open elsewhere; sweep_older_than removes it later.
pass
def __enter__(self) -> "TempFile":
return self
def __exit__(self, exc_type: type[BaseException] | None,
exc: BaseException | None, tb: TracebackType | None) -> None:
self.close()
class TempFolder:
def __init__(self, path: str) -> None:
self.full_path = path
@staticmethod
def create(prefix: str = "ic-") -> "TempFolder":
return TempFolder(tempfile.mkdtemp(prefix=prefix))
def close(self) -> None:
try:
shutil.rmtree(self.full_path)
except OSError:
# A file is still open; the OS temp cleanup handles it.
pass
def __enter__(self) -> "TempFolder":
return self
def __exit__(self, exc_type: type[BaseException] | None,
exc: BaseException | None, tb: TracebackType | None) -> None:
self.close()
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Usage: sweep old temp files at startup, then use self-deleting temp files
Source: ImproveCode, Chapter 10, Recipe 10.7 "Temp Files That Clean Up After Themselves"
Section: The improved recipe
Book page: 227 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; TempFile comes from p225. `using` blocks
become `with`; the download stream copy uses shutil.copyfileobj.
"""
from __future__ import annotations
import shutil
from collections.abc import Awaitable, Callable
from datetime import timedelta
from typing import IO
from p225_r10_7_self_cleaning_temp_file_folder import TempFile
async def run(
pdf_bytes: bytes,
output_path: str,
download: IO[bytes],
convert_to_tiff: Callable[[str, str], None],
import_async: Callable[[IO[bytes]], Awaitable[None]],
) -> None:
TempFile.sweep_older_than(timedelta(days=1)) # at startup
with TempFile.create(".pdf") as temp:
with open(temp.full_path, "wb") as f:
f.write(pdf_bytes)
convert_to_tiff(temp.full_path, output_path)
# deleted here, even if convert_to_tiff throws
with TempFile.open_scratch_stream() as scratch:
shutil.copyfileobj(download, scratch)
scratch.seek(0)
await import_async(scratch)
# the operating system deletes it on close
How it works
TempFile.Create uses Path.GetRandomFileName, which returns a random name without touching the disk, instead of Path.GetTempFileName, which creates a file and has the 65,535 limit on Windows. The file is created with FileMode.CreateNew so a name collision fails instead of handing two callers the same file. Dispose deletes it, so a using block covers every exit path, exceptions included.
OpenScratchStream is for data that never needs a path: a download staged before import, or a large intermediate result. FileOptions.DeleteOnClose asks the operating system to delete the file when the last handle closes. That includes the process being killed, which a finally block cannot handle.
All temp files live under one folder named after the application, so SweepOlderThan can safely delete anything older than a day without touching other programs' files. Call it at startup and, for long-running services, once a day from a scheduled job. The narrow catch (IOException) blocks are deliberate and commented: a file that is still in use will be removed by the next sweep, and cleanup should never crash the job that called it.
TempFolder uses Directory.CreateTempSubdirectory (.NET 7 and later), which creates a uniquely named folder in the system temp path. It is the right home for zip extraction (Recipe 10.4) or any job that produces several intermediate files.
Variations and pitfalls
- Sensitive data. Temp files are plain files. For decrypted documents or exports with personal data, use a folder with restricted permissions, or keep the data in memory when it is small enough.
On .NET Framework
Directory.CreateTempSubdirectory and FileStreamOptions are not available. Build the folder name from Path.GetTempPath() and Path.GetRandomFileName() and create it with Directory.CreateDirectory. FileOptions.DeleteOnClose and the rest of the recipe work as shown.