all Python 3tempfilefunction
tempfile.NamedTemporaryFile()
temporary files
Creates a temporary file that has a visible name in the file system, so its path f.name can be passed to other code.
Syntax
tempfile.NamedTemporaryFile(mode='w+b', ..., suffix=None, prefix=None, dir=None, delete=True, *, errors=None, delete_on_close=True)
By default the file is deleted when closed, so on Windows it cannot be reopened by name while still open, and after closing it is gone everywhere. Since Python 3.12, delete_on_close=False keeps the file after close() and deletes it only when the with block exits, so you can close it and hand it to another program. delete=False keeps the file forever, and you must remove it yourself with os.remove().
Examples
import os, tempfile
with tempfile.NamedTemporaryFile(suffix='.txt') as f:
print(f.name.endswith('.txt'), os.path.exists(f.name)) # → True True
print(os.path.exists(f.name)) # → False — удалён при закрытии
# Python 3.12+
import os, tempfile
with tempfile.NamedTemporaryFile('w', encoding='utf-8', delete_on_close=False) as f:
f.write('data')
f.close()
print(open(f.name, encoding='utf-8').read()) # → data
print(os.path.exists(f.name)) # → False
See also
Open in the full glossarydocs.python.orgReport an inaccuracy