tempfile.TemporaryFile() vs tempfile.NamedTemporaryFile()
tempfile.TemporaryFile() and tempfile.NamedTemporaryFile() 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.TemporaryFile(): Creates a temporary file that is automatically deleted when closed. Its syntax is tempfile.TemporaryFile(mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None), and it returns file-like object 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 Example of tempfile.TemporaryFile(): import tempfile
with tempfile.TemporaryFile() as f:
f.write(b"temporary data")
f.seek(0)
print(f.read()) # b"temporary data"
# File deleted after with block. Example of tempfile.NamedTemporaryFile(): with tempfile.NamedTemporaryFile(suffix=".txt") as f:
print(f.name) # "/tmp/tmpxyz.txt"
f.write(b"hello"). Read the full references for tempfile.TemporaryFile() and tempfile.NamedTemporaryFile() to see parameters, edge cases, and example code side by side. Other Tempfile Module APIs worth comparing: tempfile.mkstemp(), tempfile.mkdtemp(), tempfile.TemporaryDirectory(), tempfile.gettempdir(), tempfile.tempdir.