On this page
tempfile.TemporaryDirectory
Prev: tempfile.SpooledTemporaryFile | Up: tempfile | Next: tempfile.TemporaryFile
Rel: tempfile.gettempdir, tempfile.gettempdirb, tempfile.gettempprefix, tempfile.gettempprefixb
Ref: docs.python.org — tempfile.TemporaryDirectory
Tags: #public #python3 #stdlib #tempfile
Import
import tempfile
from tempfile import TemporaryDirectory
Signature & Overview
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False, *, delete=True)
Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example:
Methods & Attributes
TemporaryDirectory.cleanup(self)—TemporaryDirectory.cleanupmethod/property.
Usage
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory(prefix="demo_") as tmp:
p = Path(tmp) / "data.txt"
p.write_text("ok", encoding="utf-8")
assert p.exists()
assert not Path(tmp).exists()
Gotchas
- Deleted recursively on exit: The directory and everything inside it are removed when leaving the
withblock (or passdelete=Falsein Python 3.12+ to inspect failures). - Wrap in
Path(tmp):TemporaryDirectoryyields astrpath, not apathlib.Path.
REPL Inspect
from tempfile import TemporaryDirectory
help(TemporaryDirectory)
Linked from
Related notes
- tuts/python3/stdlib_module/tempfile/SpooledTemporaryFile Linked here; links to this page; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/TemporaryFile Linked here; links to this page; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/gettempdir Linked here; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/gettempdirb Linked here; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/gettempprefix Linked here; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/gettempprefixb Linked here; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/mkdtemp shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/mkstemp shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/mktemp shared tags: #stdlib, #tempfile