all Python 3tempfileterm
tempfile
module
Temporary files and directories with unique names that clean themselves up after use.
Syntax
import tempfile
tempfile creates temporary files and directories with unique names and no races: TemporaryDirectory and NamedTemporaryFile used in a with block clean up after themselves. A hand-made path like /tmp/data.txt, by contrast, collides with other processes and is left behind. mktemp is deprecated: another process can grab the name between choosing it and creating the file — use mkstemp instead.
Examples
import tempfile, pathlib
with tempfile.TemporaryDirectory(dir='.') as d:
p = pathlib.Path(d) / 'note.txt'
p.write_text('draft')
print(p.read_text()) # → draft
print(p.exists()) # → False — каталог удалён вместе с файлом
See also
Open in the full glossarydocs.python.orgReport an inaccuracy