Python tempfile — Temporary Files and Folders
Many scripts need scratch space that should not survive the job: a draft file for a tool that only reads from disk, a folder for unpacked files, a log a second program opens by name. The tempfile module creates those files and folders with unique names in a shared system folder, and the high-level forms delete themselves when the work is done. This guide creates a self-cleaning folder and file, uses unnamed and memory-first files, controls names and location, drops to the low-level calls, and ends with manual cleanup.
Written November 13, 2026 · Tested with Python 3.12.3 · 8 min read
- The main program: a folder that deletes itself
- A file with a name: NamedTemporaryFile
- A file with no name to manage: TemporaryFile
- Starting in memory: SpooledTemporaryFile
Written November 13, 2026
Tested with Python 3.12.3
What this guide is
The tempfile module creates temporary files and folders. The names include a random part, so two programs running at the same time do not pick the same scratch path in a shared folder. The high-level forms — TemporaryDirectory, NamedTemporaryFile, TemporaryFile, and SpooledTemporaryFile — work as context managers and clean up on exit. Two lower-level calls, mkstemp and mkdtemp, hand over a path and leave closing and deleting to the caller. Most work uses the high-level forms.
The main program: a folder that deletes itself
The TemporaryDirectory call creates a folder and returns its path as a string when it is used in a with statement. Files written inside live as long as the block runs, and the whole folder, contents included, is removed when the block ends:
import pathlib, tempfile
with tempfile.TemporaryDirectory() as td:
root = pathlib.Path(td)
path = root / "notes.txt"
path.write_text("draft notes\n", encoding="utf-8")
print(root.exists())
print(sorted(p.name for p in root.iterdir()))
print(path.read_text(encoding="utf-8"), end="")
saved = td
print(pathlib.Path(saved).exists())
The exact output:
True
['notes.txt']
draft notes
False
That last line is the point of the module: the caller never writes a delete step, and a crash-free run leaves no scratch folder behind. Wrapping the string path in a Path object makes the folder behave like any other folder in pathlib code.
A file with a name: NamedTemporaryFile
The NamedTemporaryFile call creates a file that is guaranteed to have a visible name, readable from the name attribute while the file is open. A second program can open that name, which is why this form exists. With the default settings the file is deleted as soon as it is closed:
import pathlib, tempfile
with tempfile.NamedTemporaryFile(mode="w+t", suffix=".txt", prefix="report-", encoding="utf-8") as handle:
handle.write("hello tempfile\n")
handle.seek(0)
print(handle.read(), end="")
name = pathlib.Path(handle.name)
print(name.name.startswith("report-"))
print(name.suffix)
print(name.exists())
saved = handle.name
print(pathlib.Path(saved).exists())
The exact output:
hello tempfile
True
.txt
True
False
The mode argument follows the same letters as open: w+t here means write and read as text. The prefix and suffix arguments shape the visible name, so a folder full of scratch files still shows which job made each one and what kind of file it is.
A file with no name to manage: TemporaryFile
The TemporaryFile call returns a file object with no visible name the caller needs to track. It opens in binary mode by default, so it reads and writes bytes, and it is destroyed as soon as it is closed:
import tempfile
with tempfile.TemporaryFile(mode="w+b") as handle:
handle.write(b"abc123")
print(handle.tell())
handle.seek(0)
print(handle.read())
print(handle.closed)
print(handle.closed)
The exact output:
6
b'abc123'
False
True
Pick this form when the scratch data never leaves the current program: intermediate bytes between two steps, a buffer a library writes to and the same code reads back. If another program must open the file by name, use NamedTemporaryFile instead.
Starting in memory: SpooledTemporaryFile
The SpooledTemporaryFile call keeps its data in memory until the data grows past the max_size argument, or until its rollover method is called, and only then writes it to a real file on disk. Small scratch data may never touch the disk at all:
import tempfile
with tempfile.SpooledTemporaryFile(max_size=10, mode="w+b") as handle:
handle.write(b"12345")
handle.seek(0)
print(handle.read())
handle.rollover()
handle.seek(0)
print(handle.read())
print(handle.tell())
The exact output:
b'12345'
b'12345'
5
The read before rollover and the read after return the same bytes; rollover changes where the data lives, not what it holds. This form suits uploads and generated files whose final size is unknown at the start: small ones stay in memory, large ones spill to disk by rule instead of by surprise.
Controlling the name and the folder
Every creator in the module accepts prefix, suffix, and dir arguments. The dir argument places the file or folder inside a chosen parent instead of the system temporary folder. This program places a named file inside a TemporaryDirectory, so both layers clean up:
import pathlib, tempfile
with tempfile.TemporaryDirectory() as td:
root = pathlib.Path(td)
with tempfile.NamedTemporaryFile(mode="w+t", suffix=".log", prefix="job-", dir=td, encoding="utf-8", delete=False) as handle:
handle.write("job log\n")
name = pathlib.Path(handle.name)
print(name.name.startswith("job-"))
print(name.suffix)
print(name.parent == root)
print(name.read_text(encoding="utf-8"), end="")
name.unlink()
print(name.exists())
The exact output:
True
.log
True
job log
False
Passing delete as false keeps the file after its handle closes, so the program can read it back by name; the caller then owns the delete step, shown here with unlink. A suffix needs its leading dot when the name should end in an extension — the module adds no dot on its own.
The low-level calls: mkstemp and mkdtemp
The mkstemp call creates a file in the most secure way the platform offers and returns a pair: a low-level file descriptor and the absolute path. It does not return a file object, so the caller writes through the descriptor, closes it, and deletes the file. The mkdtemp call does the same job for a folder:
import os, pathlib, shutil, tempfile
fd, raw_path = tempfile.mkstemp(suffix=".txt", prefix="data-")
try:
os.write(fd, b"from mkstemp\n")
os.close(fd)
path = pathlib.Path(raw_path)
print(path.name.startswith("data-"))
print(path.suffix)
print(path.read_bytes())
finally:
pathlib.Path(raw_path).unlink(missing_ok=True)
print(pathlib.Path(raw_path).exists())
folder = tempfile.mkdtemp(prefix="work-")
try:
root = pathlib.Path(folder)
print(root.name.startswith("work-"))
(root / "a.txt").write_text("a\n", encoding="utf-8")
print(sorted(p.name for p in root.iterdir()))
finally:
shutil.rmtree(folder)
print(pathlib.Path(folder).exists())
The exact output:
True
.txt
b'from mkstemp\n'
False
True
['a.txt']
False
Both cleanups sit in finally blocks, so the file and folder are removed even when the work between raises an error. That manual burden is the trade: reach for these calls only when code needs the descriptor itself, or a path with no open file attached. Day-to-day scripts are shorter and safer with the context-manager forms.
Manual cleanup and the system folder
The gettempdir function returns the folder the module uses by default, and gettempprefix returns the default name prefix. A TemporaryDirectory object kept outside a with statement is removed by calling its cleanup method. A file created with delete set to false is removed by the caller when it is no longer needed:
import pathlib, tempfile
print(pathlib.Path(tempfile.gettempdir()).is_dir())
print(tempfile.gettempprefix())
with tempfile.NamedTemporaryFile(mode="w+t", suffix=".txt", encoding="utf-8", delete=False) as handle:
handle.write("keep for now\n")
saved = pathlib.Path(handle.name)
print(saved.exists())
print(saved.read_text(encoding="utf-8"), end="")
saved.unlink()
print(saved.exists())
folder = tempfile.TemporaryDirectory()
inner = pathlib.Path(folder.name)
print(inner.exists())
folder.cleanup()
print(inner.exists())
The exact output:
True
tmp
True
keep for now
False
True
False
The system folder itself is not the caller's to clean; only the files and folders the program created inside it are. The default folder can be changed for a whole run by setting the TMPDIR, TEMP, or TMP environment variable before the program starts, which is how a job points scratch space at a larger disk.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| Scratch folder | TemporaryDirectory | Folder and contents removed on exit |
| File another program opens | NamedTemporaryFile | Visible name, deleted on close |
| Scratch bytes in one program | TemporaryFile | No name to track |
| Small file, may grow | SpooledTemporaryFile | Memory first, disk past max_size |
| Named file in a chosen folder | NamedTemporaryFile with dir | Prefix, suffix, and parent set |
| Descriptor-level control | mkstemp | Caller closes and deletes |
| Folder-level control | mkdtemp | Caller deletes the tree |
Checklist
- Use a with statement for the high-level forms, so cleanup runs even when the block raises.
- Use NamedTemporaryFile when another program needs the path, and TemporaryFile when it does not.
- Set a prefix and suffix when scratch files must be readable in a shared folder listing.
- Pass delete as false only when the file must outlive its handle, and write the delete step in the same code.
- Wrap mkstemp and mkdtemp work in try and finally, so the close and delete steps always run.
- Keep real output out of temporary files: if the job fails, the scratch copy is gone by design.
Related guides on this site
- Python pathlib — Paths, Parts, and Files — the Path objects used to work inside a temporary folder.
- Python shutil — Copy, Move, Archive, and Clean Up — copying and deleting real files and trees that must survive the job.
- Python Files — open, read, write, and with — the open modes and with statement the temporary file forms build on.
- Python
zipfile— Create, List, Read, and Extract — packing files into an archive, often staged in a temporary folder first.
Sources
- Python Standard Library,
tempfile— TemporaryFile, NamedTemporaryFile with delete and delete_on_close, SpooledTemporaryFile and rollover, TemporaryDirectory and cleanup, mkstemp and mkdtemp with manual cleanup, gettempdir and gettempprefix, and the prefix, suffix, and dir arguments. - Python Standard Library, pathlib — the Path objects used for the temporary folder and file paths.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.