tempfile.mkstemp() vs tempfile.mkdtemp()
tempfile.mkstemp() and tempfile.mkdtemp() are both Python Tempfile Module APIs, and choosing between them is a common point of confusion. This page compares their syntax, parameters, return values, and typical use cases so you can pick the right one. tempfile.mkstemp(): Creates a temporary file and returns a (fd, path) tuple. Caller must close and delete. Its syntax is tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False), and it returns (fd, pathname) tuple tempfile.mkdtemp(): Creates a temporary directory that persists after creation. Its syntax is tempfile.mkdtemp(suffix=None, prefix=None, dir=None), and it returns path string Example of tempfile.mkstemp(): import os, tempfile
fd, path = tempfile.mkstemp()
os.write(fd, b"data")
os.close(fd)
os.remove(path). Example of tempfile.mkdtemp(): import os, tempfile
d = tempfile.mkdtemp()
print(d) # "/tmp/tmpXXXXXX/"
# Caller must delete: os.rmdir(d). Read the full references for tempfile.mkstemp() and tempfile.mkdtemp() to see parameters, edge cases, and example code side by side. Other Tempfile Module APIs worth comparing: tempfile.TemporaryFile(), tempfile.NamedTemporaryFile(), tempfile.TemporaryDirectory(), tempfile.gettempdir(), tempfile.tempdir.