tempfile.NamedTemporaryFile
Prev: tempfile.mktemp | Up: tempfile | Next: tempfile.SpooledTemporaryFile
Rel: tempfile.gettempdir, tempfile.gettempdirb, tempfile.gettempprefix, tempfile.gettempprefixb
Ref: docs.python.org — tempfile.NamedTemporaryFile
Tags: #public #python3 #stdlib #tempfile
Import
import tempfile
from tempfile import NamedTemporaryFile
Signature & Overview
tempfile.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None, delete_on_close=True)
Create and return a temporary file.
Usage
from pathlib import Path
import tempfile
with tempfile.NamedTemporaryFile("w+", suffix=".txt", encoding="utf-8") as f:
f.write("hello")
f.flush()
assert Path(f.name).read_text(encoding="utf-8") == "hello"
Gotchas
- Windows reopen quirk: On Windows, another process (or a second
open(f.name)) cannot open the file while it's still open unless you passdelete_on_close=False(Python 3.12+) andf.close()first. - Flush before external tools read
f.name: Buffered writes aren't visible to subprocesses untilf.flush()orf.close().
REPL Inspect
from tempfile import NamedTemporaryFile
help(NamedTemporaryFile)
Linked from
Related notes
- tuts/python3/stdlib_module/tempfile/mktemp Linked here; links to this page; shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/SpooledTemporaryFile 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/mkdtemp shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/mkstemp shared tags: #stdlib, #tempfile
- tuts/python3/stdlib_module/tempfile/TemporaryDirectory shared tags: #stdlib, #tempfile