TemporaryDirectory, NamedTemporaryFile
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False, *, delete=True)
tempfile.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 a temporary directory or a named temporary file, and control when the file is deleted.
| Parameter | Description |
|---|---|
prefix, suffix, dir | Optional name parts and a parent directory. The example always passes dir= so files stay in the script's temporary tree. |
delete | If True (the default), TemporaryDirectory removes the directory on exit, and NamedTemporaryFile removes the file according to delete_on_close and context exit. |
delete_on_close | If False, closing the file does not delete it; the file is still deleted when the context exits if delete is True. Measured on Python 3.13.12. |
Returns: TemporaryDirectory yields the directory path. NamedTemporaryFile yields a file object with a .name attribute.
- Do not print .name or the directory path in a test that must stay deterministic. The example only prints suffixes, prefixes, and existence booleans.
import os
import tempfile
with tempfile.TemporaryDirectory(prefix="py-ref-") as folder:
print("dir-prefix", os.path.basename(folder).startswith("py-ref-"))
path = os.path.join(folder, "note.txt")
with open(path, "w", encoding="utf-8") as file:
file.write("hello")
with open(path, encoding="utf-8") as file:
print("content", file.read())
existed = os.path.isdir(folder)
print("dir-after-exit", os.path.isdir(folder))
print("dir-existed", existed)
with tempfile.TemporaryDirectory(prefix="py-ref-") as folder:
with tempfile.NamedTemporaryFile(
mode="w+",
encoding="utf-8",
suffix=".txt",
prefix="n-",
dir=folder,
delete=True,
) as file:
file.write("named")
file.flush()
name = file.name
print("named-suffix", name.endswith(".txt"))
print("named-prefix", os.path.basename(name).startswith("n-"))
print("exists-while-open", os.path.exists(name))
print("exists-after-close", os.path.exists(name))
with tempfile.NamedTemporaryFile(
mode="w+",
encoding="utf-8",
suffix=".txt",
prefix="k-",
dir=folder,
delete=True,
delete_on_close=False,
) as file:
file.write("keep")
file.flush()
kept = file.name
file.close()
print("exists-after-close-delete-on-close-false", os.path.exists(kept))
print("exists-after-context", os.path.exists(kept))
Expected output
dir-prefix True
content hello
dir-after-exit False
dir-existed True
named-suffix True
named-prefix True
exists-while-open True
exists-after-close False
exists-after-close-delete-on-close-false True
exists-after-context False