On this page
  1. tempfile
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Passing a Temporary File to an External Command (Cross-Platform)
  7. 2. Spooled In-Memory Buffer That Spills to Disk
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes