Filesystem and I/O Modules
tempfile
Creates temporary files and directories with generated names. TemporaryDirectory cleans up its own directory on context exit; TemporaryFile provides an automatically cleaned file object. NamedTemporaryFile has platform-dependent reopening and deletion constraints. Do not construct predictable temporary filenames manually.
Formal Syntax & Structure
python syntaxpython
import tempfileReturn Value
module
Module namespace available through import; import is a statement, not a value-returning expression.
Working Example
Example Snippetpython
from tempfile import TemporaryDirectoryfrom pathlib import Pathwith TemporaryDirectory() as folder: path = Path(folder)/"scratch.txt" path.write_text("draft", encoding="utf-8") print(path.exists())print(path.exists())