On this page
tempfile.mkstemp
Prev: tempfile.mkdtemp | Up: tempfile | Next: tempfile.mktemp
Rel: tempfile.gettempdir, tempfile.gettempdirb, tempfile.gettempprefix, tempfile.gettempprefixb
Ref: docs.python.org — tempfile.mkstemp
Tags: #public #python3 #stdlib #tempfile
Import
import tempfile
from tempfile import mkstemp
Signature & Overview
tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)
User-callable function to create and return a unique temporary file. The return value is a pair (fd, name) where fd is the file descriptor returned by os.open, and name is the filename.
Usage
import os
import tempfile
fd, path = tempfile.mkstemp(suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write("atomic data")
finally:
os.unlink(path)
Gotchas
- Returns an open OS file descriptor
(fd, path): You must closefd(viaos.close(fd)oros.fdopen(fd, ...)) and manuallyos.unlink(path)when done. - Prefer
NamedTemporaryFilefor most tasks: Reach formkstemp()mainly for atomic write-and-os.replace()patterns in a target directory (dir=target.parent).
REPL Inspect
from tempfile import mkstemp
help(mkstemp)
Linked from
Related notes
- tuts/python3/stdlib_module/tempfile/mkdtemp Linked here; links to this page; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/mktemp Linked here; links to this page; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile/gettempdir Linked here; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/gettempdirb Linked here; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/gettempprefix Linked here; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/gettempprefixb Linked here; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/NamedTemporaryFile shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/SpooledTemporaryFile shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/TemporaryDirectory shared tags: #stdlib, #tempfile