tempfile

Updated March 13, 2026 · Modules
stdlib files temporary security

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

ParameterTypeDefaultDescription
modestr'w+b'File mode (similar to built-in open())
bufferingint-1Buffering policy (-1 for default)
encodingstrNoneCharacter encoding
newlinestrNoneNewline mode
suffixstrNoneString appended to the filename
prefixstrNoneString prefixed to the filename
dirstrNoneDirectory to create the file in
errorsstrNoneError 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

ParameterTypeDefaultDescription
modestr'w+b'File mode
bufferingint-1Buffering policy
encodingstrNoneCharacter encoding
suffixstrNoneString appended to filename
prefixstrNoneString prefixed to filename
dirstrNoneDirectory to create file in
deleteboolTrueIf 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

ParameterTypeDefaultDescription
suffixstrNoneString appended to directory name
prefixstrNoneString prefixed to directory name
dirstrNoneParent 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

ParameterTypeDefaultDescription
suffixstrNoneString appended to filename
prefixstrNoneString prefixed to filename
dirstrNoneDirectory to create file in
textboolFalseIf 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

ParameterTypeDefaultDescription
suffixstrNoneString appended to directory name
prefixstrNoneString prefixed to directory name
dirstrNoneParent 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

ErrorCause
PermissionErrorDirectory is not writable or lacks permissions
OSErrorSystem limit for temporary files exceeded
FileNotFoundErrorSpecified dir does not exist

See Also