Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

os.tempfile

import os

Everything here is re-exported by os, so import os is enough and the names are called as os.*. Importing os.tempfile on its own works too and reaches the same definitions.

Locating the platform’s temporary-file directory and creating uniquely named scratch files/directories inside it without a check-then-create race: create_temp_file()/create_temp_dir() reserve the path atomically (the same guarantee the Unix mkstemp() family gives), so two concurrent callers can never be handed the same path.

Functions

temp_dir()

os.temp_dir() -> string

The platform’s directory for temporary files (e.g. /tmp on Unix, whatever %TEMP% points to on Windows).

Returns string

create_temp_file()

os.create_temp_file(prefix: ?string, suffix: ?string) -> string

Atomically creates a new, empty, uniquely named file inside temp_dir() and returns its path. The file is created (and left open-then-closed) purely to reserve the name without a race between checking whether it exists and creating it: this function only hands back the path; open it yourself with file() to actually read or write it.

Parameters

  • prefix (?string) — Default ''.
  • suffix (?string) — Default ''.

Returns string

Raises Error if a unique name couldn’t be found, or the file couldn’t be created.

Note: the caller is responsible for deleting the file (via file(path).delete()) once it’s no longer needed; nothing cleans temp files up automatically.

create_temp_dir()

os.create_temp_dir(prefix: ?string) -> string

Atomically creates a new, empty, uniquely named directory inside temp_dir() and returns its path.

Parameters

  • prefix (?string) — Default ''.

Returns string

Raises Error if a unique name couldn’t be found, or the directory couldn’t be created.

Note: the caller is responsible for removing the directory (via os.remove_dir(path, true)) once it’s no longer needed; nothing cleans temp directories up automatically.


2021, Richard Ore and Zuri contributors