tempfile — temporary files and directories

TemporaryDirectory, NamedTemporaryFile, mkstemp, and SpooledTemporaryFile on Python 3.13.12, using only isolated temporary trees and never printing random paths.

tempfile creates temporary files and directories. Other pages on this site already use TemporaryDirectory as a sandbox for pathlib, csv, os, and io examples. This page documents tempfile itself. Every file operation stays inside a TemporaryDirectory created by the same script. The examples never print the random absolute path, and they do not read the home directory or other user files.

Examples were checked on Python 3.13.12. NamedTemporaryFile.delete_on_close is part of the 3.12+ API and was measured here on 3.13.12.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

TemporaryDirectory and NamedTemporaryFile

TemporaryDirectory(prefix="py-ref-") creates a directory and removes it when the with-block exits. The example only reports that the basename starts with the chosen prefix, writes a controlled file name, and then checks that the directory is gone.

NamedTemporaryFile(..., delete=True) removes the file when the context closes. delete_on_close=False, with delete=True, keeps the file after an explicit close() and still deletes it when the context manager exits. The example places both files inside the same TemporaryDirectory so nothing is left behind.

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.

ParameterDescription
prefix, suffix, dirOptional name parts and a parent directory. The example always passes dir= so files stay in the script's temporary tree.
deleteIf True (the default), TemporaryDirectory removes the directory on exit, and NamedTemporaryFile removes the file according to delete_on_close and context exit.
delete_on_closeIf 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.
python
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

Related: shutil, os

Official documentation →

mkstemp and SpooledTemporaryFile

mkstemp returns a raw file descriptor and a path. You must close the descriptor yourself. The example writes bytes, closes the fd, reads the content, and unlinks the file inside the same TemporaryDirectory.

SpooledTemporaryFile(max_size=8) starts as an in-memory file and can roll over to a real temporary file once it grows. The example only checks that a write longer than max_size still reads back the same text. It does not print a filesystem path.

mkstemp, SpooledTemporaryFile

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)
tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

Create a low-level temporary file descriptor, or a spooled file that can stay in memory up to max_size.

ParameterDescription
dirParent directory for mkstemp. Always set this in examples that must not write into an unknown default location.
textIf True, the file is opened in text mode on some platforms. The example uses text=False and os.write with bytes.
max_sizeThe in-memory size limit for SpooledTemporaryFile, in bytes.

Returns: mkstemp returns (fd, path). SpooledTemporaryFile returns a file-like object.

  • Leaving an mkstemp descriptor open leaks a file. The example closes it in a finally block and then unlinks the path.
python
import os
import tempfile

with tempfile.TemporaryDirectory(prefix="py-ref-") as folder:
    fd, name = tempfile.mkstemp(suffix=".dat", prefix="m-", dir=folder, text=False)
    try:
        print("fd-is-int", isinstance(fd, int))
        print("name-prefix", os.path.basename(name).startswith("m-"))
        print("name-suffix", name.endswith(".dat"))
        os.write(fd, b"xyz")
    finally:
        os.close(fd)
    with open(name, "rb") as file:
        print("content", file.read())
    os.unlink(name)
    print("unlinked", not os.path.exists(name))

with tempfile.SpooledTemporaryFile(max_size=8, mode="w+", encoding="utf-8") as spool:
    spool.write("abcdefghij")
    spool.seek(0)
    print("spooled", spool.read())

Expected output

fd-is-int True
name-prefix True
name-suffix True
content b'xyz'
unlinked True
spooled abcdefghij

Official documentation →