Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Files, Paths and Text I/O

The tempfile module

Reference for Python's tempfile module: TemporaryFile, NamedTemporaryFile, TemporaryDirectory, mkstemp, gettempdir and automatic cleanup.

tempfile creates temporary files and folders safely. It picks a unique name in the system's temporary folder, creates the file so nobody else can claim the name first, and, with the right function, deletes it automatically when you are finished.

Use it for scratch data: a download to verify before saving, a file to hand to a program that wants a path, or a throwaway folder in a test. Always prefer it to inventing names like /tmp/myapp.tmp, which collide and can be hijacked.

Python
import tempfile

with tempfile.TemporaryDirectory() as folder:
    print("working in a folder that will vanish")

Try it

Python Temporary files and folders that clean up after themselves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Names, locations and low-level mkstemp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
tempfile.TemporaryFile(mode="w+b", suffix=None, prefix=None, dir=None, encoding=None)
tempfile.NamedTemporaryFile(mode="w+b", suffix=None, prefix=None, dir=None, delete=True)
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)
tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)
tempfile.mkdtemp(suffix=None, prefix=None, dir=None)
tempfile.gettempdir()
Name Description
mode File mode as in open(). The default is binary read-write ("w+b"); use "w+" for text.
suffix, prefix Text added to the end or start of the generated name, such as ".csv".
dir Create inside this folder instead of the system temporary folder.
delete NamedTemporaryFile only: remove the file on close (default True). Python 3.12 adds delete_on_close.
encoding, newline Same meaning as in open(), for text mode.

Return value: TemporaryFile, NamedTemporaryFile and SpooledTemporaryFile return file-like objects (use them in with). TemporaryDirectory returns an object whose with ... as name value is the folder path. mkstemp() returns (file_descriptor, path), mkdtemp() a path, gettempdir() a string.

Raises: FileExistsError if a unique name cannot be found, FileNotFoundError if dir does not exist, PermissionError.

Usage notes

  • Use with. Files and folders created by the context-manager classes are deleted when the block ends, even if an exception occurs.
  • TemporaryFile may have no name at all on Unix (it is unlinked right away), so f.name is not a usable path. Use NamedTemporaryFile when another program needs the path.
  • Windows and reopening. A NamedTemporaryFile that is still open generally cannot be opened a second time by name on Windows. Close it first with delete=False (and delete it yourself), or use delete_on_close=False on Python 3.12+.
  • mkstemp() and mkdtemp() do not clean up. You own the result and must remove it. mkstemp also leaves you an open file descriptor to close, for instance via os.fdopen.
  • Security. The created file has restrictive permissions (readable only by the current user), and the name is unpredictable. Do not use the deprecated mktemp(), which only invents a name and invites race conditions.
  • Where it lives. gettempdir() looks at the TMPDIR, TEMP and TMP environment variables first, then system defaults. Large temporary files can fill a small /tmp; pass dir= to choose a roomy disk.
  • SpooledTemporaryFile keeps data in memory until it exceeds max_size, then moves it to disk; handy for uploads of unknown size.
  • Version notes. NamedTemporaryFile(delete_on_close=...) and TemporaryDirectory(delete=False) were added in Python 3.12; check your version before relying on them.