Python Basics: Creating Temporary Files with tempfile
Python’s standard-library tempfile module creates temporary files and directories for tests and intermediate results.
Use Python 3.12 or newer on Linux. Each example creates a fresh disposable directory. Warning: leaving a TemporaryDirectory context removes that directory and everything inside it. Keep anything you need elsewhere before the block ends.
Work inside a temporary directory
Save as demo_tempfile_1.py:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as temporary_directory:
workspace = Path(temporary_directory)
report_path = workspace / "report.txt"
with report_path.open("x", encoding="utf-8") as report_file:
report_file.write("Processed 3 records\n")
print(report_path.read_text(encoding="utf-8"), end="")
print("Inside context:", workspace.exists())
print("After context:", workspace.exists())Run:
python3 demo_tempfile_1.pyOutput:
Processed 3 records
Inside context: True
After context: FalseTemporaryDirectory() supplies a unique directory name. Printing its state instead of its generated path keeps output predictable. Mode "x" creates a file exclusively and raises FileExistsError instead of overwriting an existing file.
Read back a temporary text file
NamedTemporaryFile() provides an open file with a filesystem name. With its default deletion settings, closing it removes the file. The outer context removes the directory.
Save as demo_tempfile_2.py:
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
with TemporaryDirectory() as temporary_directory:
with NamedTemporaryFile(
mode="w+t", encoding="utf-8", suffix=".txt",
dir=temporary_directory,
) as temporary_file:
temporary_path = Path(temporary_file.name)
temporary_file.write("Ready for import\n")
temporary_file.seek(0)
print(temporary_file.read(), end="")
print("File exists:", temporary_path.exists())
print("After close:", temporary_path.exists())Run:
python3 demo_tempfile_2.pyOutput:
Ready for import
File exists: True
After close: FalseThe default mode is binary ("w+b"). Here "w+t" accepts text, and + permits reading and writing. After writing, the cursor is at the end; seek(0) moves it back before reading.
Cleanup also runs when a normal Python exception leaves the block. Abrupt process termination can leave files behind. Temporary paths are unsuitable for lasting results.
References
Acknowledgements
This post was created with assistance from AI.