On this page
tempfile
Prev: tarfile | Up: stdlib_module | Next: termios
Rel: pathlib, os, io, time, fileinput
Ref: docs.python.org — tempfile
Tags: #public #python3 #stdlib
Import
import tempfile
Overview
Creates secure, race-free temporary files and directories with automatic cleanup on exit. Reach for tempfile.TemporaryDirectory() for scratch workspaces in tests and build pipelines, or NamedTemporaryFile when an external tool needs a filesystem path.
Quick Start
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory(prefix="build_") as tmpdir:
artifact = Path(tmpdir) / "out.txt"
artifact.write_text("ephemeral", encoding="utf-8")
assert artifact.read_text(encoding="utf-8") == "ephemeral"
# Directory and contents are deleted automatically here
Implementation Walkthrough
1. Passing a Temporary File to an External Command (Cross-Platform)
On Windows, an open NamedTemporaryFile cannot be opened a second time by another process unless delete_on_close=False (Python 3.12+) is used and the handle is closed first:
import tempfile
from pathlib import Path
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", suffix=".json", delete_on_close=False) as tf:
tf.write('{"ok": true}\n')
tf.close()
assert Path(tf.name).read_text(encoding="utf-8") == '{"ok": true}\n'
2. Spooled In-Memory Buffer That Spills to Disk
SpooledTemporaryFile stays in RAM until it exceeds max_size, then transparently rolls over to disk:
import tempfile
with tempfile.SpooledTemporaryFile(max_size=64 * 1024, mode="w+b") as buf:
buf.write(b"small payload stays in memory")
buf.seek(0)
assert buf.read().startswith(b"small")
Gotchas & Boundaries
- Avoid
mktemp(): It has a classic TOCTOU race condition; always useTemporaryDirectory,NamedTemporaryFile, ormkstemp(). - Close
mkstemp()'s raw file descriptor:fd, path = tempfile.mkstemp()returns an open OS file descriptor that you must close (os.close(fd)) and unlink manually. - Create temp files in the target directory for atomic replaces: If you plan to
os.replace()into a destination, passdir=target.parentso both live on the same filesystem.
Common Functions
- tempfile.gettempdir() —
gettempdir()— Returns tempfile.tempdir as str. - tempfile.gettempdirb() —
gettempdirb()— Returns tempfile.tempdir as bytes. - tempfile.gettempprefix() —
gettempprefix()— The default prefix for temporary directories as string. - tempfile.gettempprefixb() —
gettempprefixb()— The default prefix for temporary directories as bytes. - tempfile.mkdtemp() —
mkdtemp(suffix=None, prefix=None, dir=None)— User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. - tempfile.mkstemp() —
mkstemp(suffix=None, prefix=None, dir=None, text=False)— User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename. - tempfile.mktemp() —
mktemp(suffix='', prefix='tmp', dir=None)— User-callable function to return a unique temporary file name. The file is not created. - tempfile.NamedTemporaryFile() —
NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None, delete_on_close=True)— Create and return a temporary file. - tempfile.TemporaryFile() —
TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)— Create and return a temporary file.
Classes & Objects
- tempfile.SpooledTemporaryFile — Temporary file wrapper, specialized to switch from BytesIO or StringIO to a real file when it exceeds a certain size or when a fileno is needed. (Methods:
.close(),.closed(),.detach(),.encoding(),.errors(),.fileno()) - tempfile.TemporaryDirectory — Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example: (Methods:
.cleanup())
Constants & Attributes
tempfile.TMP_MAX(int) =20tempfile.tempdir(NoneType) =None
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/tarfile
- tuts/python3/stdlib_module/tempfile/gettempdir
- tuts/python3/stdlib_module/tempfile/gettempdirb
- tuts/python3/stdlib_module/tempfile/gettempprefix
- tuts/python3/stdlib_module/tempfile/gettempprefixb
- tuts/python3/stdlib_module/tempfile/mkdtemp
- tuts/python3/stdlib_module/tempfile/mkstemp
- tuts/python3/stdlib_module/tempfile/mktemp
- tuts/python3/stdlib_module/tempfile/NamedTemporaryFile
- tuts/python3/stdlib_module/tempfile/SpooledTemporaryFile
- tuts/python3/stdlib_module/tempfile/TemporaryDirectory
- tuts/python3/stdlib_module/tempfile/TemporaryFile
- tuts/python3/stdlib_module/termios
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tarfile Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/gettempdir Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/gettempdirb Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/gettempprefix Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/gettempprefixb Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/mkdtemp Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/mkstemp Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/mktemp Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/NamedTemporaryFile Linked here; links to this page; shared tags: #stdlib