tempfile.NamedTemporaryFile() vs tempfile.mkstemp()
tempfile.NamedTemporaryFile() and tempfile.mkstemp() 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.NamedTemporaryFile(): Creates a temporary file with a visible name in the filesystem. Its syntax is tempfile.NamedTemporaryFile(mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True), and it returns file-like object with .name attribute 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 Example of tempfile.NamedTemporaryFile(): with tempfile.NamedTemporaryFile(suffix=".txt") as f:
print(f.name) # "/tmp/tmpxyz.txt"
f.write(b"hello"). Example of tempfile.mkstemp(): import os, tempfile
fd, path = tempfile.mkstemp()
os.write(fd, b"data")
os.close(fd)
os.remove(path). Read the full references for tempfile.NamedTemporaryFile() and tempfile.mkstemp() to see parameters, edge cases, and example code side by side. Other Tempfile Module APIs worth comparing: tempfile.TemporaryFile(), tempfile.mkdtemp(), tempfile.TemporaryDirectory(), tempfile.gettempdir(), tempfile.tempdir.