Python Glossary Русский

Python 3.2+tempfileterm

tempfile.TemporaryDirectory

directories and paths

Creates a temporary directory and removes it together with all its contents when the with block exits.

Syntax

with tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False, *, delete=True) as path: ...

Inside with, the variable receives a path string, not an object: build Path(tmp) / 'a.txt' yourself. Without with, the directory is removed only by cleanup() or when the object is garbage-collected, with a ResourceWarning. If a file inside is still open (typical on Windows), removal fails; ignore_cleanup_errors=True (3.10+) silences that, and delete=False (3.12+) keeps the directory.

Examples

import os, tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
    print(type(tmp).__name__)  # → str
    (Path(tmp) / 'a.txt').write_text('x', encoding='utf-8')
    print(os.listdir(tmp))  # → ['a.txt']
print(os.path.exists(tmp))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy