Python Tempfile Module
The tempfile module creates temporary files and directories safely.
import tempfile
Use tempfile for data that should exist only while your program is running, such as test output, downloads, or intermediate files.
TemporaryFile()
TemporaryFile creates a file object that is cleaned up automatically.
import tempfile
with tempfile.TemporaryFile(mode='w+t') as temp:
temp.write('hello')
temp.seek(0)
print(temp.read())
hello
The file is removed automatically when the with block ends.
NamedTemporaryFile()
NamedTemporaryFile gives you a path on disk.
import tempfile
with tempfile.NamedTemporaryFile(mode='w+t') as temp:
print(bool(temp.name))
True
This is useful when another API needs a filename instead of a file object.
TemporaryDirectory()
Temporary directories are useful for tests and short-lived workspaces.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as directory:
file_path = Path(directory) / 'notes.txt'
file_path.write_text('draft')
print(file_path.exists())
True
Files inside the directory are removed with the directory when the block exits.
Choosing a temporary location
gettempdir() shows the directory Python uses by default.
import tempfile
print(bool(tempfile.gettempdir()))
True