tempfile
The tempfile module creates temporary files and directories for intermediate data that does not need to persist. It handles security concerns like race conditions and ensures proper cleanup. This module is essential for tasks such as caching, testing, and handling uploaded files.
Syntax
import tempfile
TemporaryFile
Creates an anonymous temporary file that is automatically deleted when closed.
tempfile.TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, errors=None)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
mode | str | 'w+b' | File mode (similar to built-in open()) |
buffering | int | -1 | Buffering policy (-1 for default) |
encoding | str | None | Character encoding |
newline | str | None | Newline mode |
suffix | str | None | String appended to the filename |
prefix | str | None | String prefixed to the filename |
dir | str | None | Directory to create the file in |
errors | str | None | Error handling scheme |
Example
with tempfile.TemporaryFile(mode='w+', suffix='.txt') as f:
f.write('Temporary data here')
f.seek(0)
print(f.read())
# Output: Temporary data here
# File is deleted after exiting the context
NamedTemporaryFile
Creates a temporary file with a visible name that persists until explicitly deleted.
tempfile.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, errors=None)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
mode | str | 'w+b' | File mode |
buffering | int | -1 | Buffering policy |
encoding | str | None | Character encoding |
suffix | str | None | String appended to filename |
prefix | str | None | String prefixed to filename |
dir | str | None | Directory to create file in |
delete | bool | True | If True, deletes file on close |
Example
with tempfile.NamedTemporaryFile(mode='w', suffix='.log', delete=False) as f:
f.write('Log entry 1\n')
print(f'File path: {f.name}')
# File persists because delete=False
TemporaryDirectory
Creates a temporary directory that is automatically deleted when exiting the context.
tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
suffix | str | None | String appended to directory name |
prefix | str | None | String prefixed to directory name |
dir | str | None | Parent directory to create in |
Example
with tempfile.TemporaryDirectory(prefix='myapp_') as tmpdir:
import os
filepath = os.path.join(tmpdir, 'data.txt')
with open(filepath, 'w') as f:
f.write('Temp data')
print(f'Created: {tmpdir}')
# Directory automatically cleaned up
mkstemp
Creates a temporary file and returns a tuple of (file descriptor, path). The file is not automatically deleted.
tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
suffix | str | None | String appended to filename |
prefix | str | None | String prefixed to filename |
dir | str | None | Directory to create file in |
text | bool | False | If True, open in text mode |
Example
fd, path = tempfile.mkstemp(prefix='debug_', suffix='.tmp')
print(f'File descriptor: {fd}, path: {path}')
# Must manually close and delete
import os
os.close(fd)
os.unlink(path)
mkdtemp
Creates a temporary directory and returns its path. The directory is not automatically deleted.
tempfile.mkdtemp(suffix=None, prefix=None, dir=None)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
suffix | str | None | String appended to directory name |
prefix | str | None | String prefixed to directory name |
dir | str | None | Parent directory to create in |
Example
tmpdir = tempfile.mkdtemp(prefix='cache_')
print(f'Created: {tmpdir}')
# Must manually clean up
import shutil
shutil.rmtree(tmpdir)
gettempdir
Returns the default directory for temporary files.
tempfile.gettempdir()
Example
print(tempfile.gettempdir())
# Output: /var/folders/... (platform-dependent)
gettempdirb
Returns the default directory for temporary files as bytes.
tempfile.gettempdirb()
Example
print(tempfile.gettempdirb())
# Output: b'/var/folders/...'
gettempprefix
Returns the prefix used for temporary filenames as a string.
tempfile.gettempprefix()
Example
print(tempfile.gettempprefix())
# Output: tmp
gettempprefixb
Returns the prefix used for temporary filenames as bytes.
tempfile.gettempprefixb()
Example
print(tempfile.gettempprefixb())
# Output: b'tmp'
Common Patterns
Processing uploaded files
def handle_upload(uploaded_file):
with tempfile.NamedTemporaryFile(delete=False) as tmp:
shutil.copyfileobj(uploaded_file, tmp)
tmp_path = tmp.name
try:
# Process the temporary file
result = process_file(tmp_path)
return result
finally:
os.unlink(tmp_path)
Caching intermediate results
def cache_results(key, compute_fn):
cache_file = os.path.join(tempfile.gettempdir(), f'cache_{key}')
if os.path.exists(cache_file):
with open(cache_file) as f:
return f.read()
result = compute_fn()
with open(cache_file, 'w') as f:
f.write(result)
return result
Errors
| Error | Cause |
|---|---|
PermissionError | Directory is not writable or lacks permissions |
OSError | System limit for temporary files exceeded |
FileNotFoundError | Specified dir does not exist |