Python tempfile Module
Example
Create a temporary file and directory:
import tempfile
with tempfile.TemporaryFile(mode='w+') as f:
f.write('Hello from Emil')
f.seek(0)
print(f'Content: {f.read()}')
Try it Yourself »
Definition and Usage
The tempfile module creates temporary files and directories securely.
Use it to generate temporary storage that is automatically cleaned up, preventing security risks and disk clutter.
Members
Member | Description |
---|---|
NamedTemporaryFile() | Create a named temporary file. |
SpooledTemporaryFile() | Create temporary file that uses memory until size exceeds threshold. |
TemporaryDirectory() | Create temporary directory (context manager). |
TemporaryFile() | Create temporary file that is automatically deleted. |
gettempdir() | Return the directory used for temporary files. |
mkdtemp() | Create a temporary directory and return its path. |
mkstemp() | Create a temporary file and return (fd, path). |
mktemp() | Return a unique temporary file name (deprecated, insecure). |