Python Glossary Русский

all Python 3tempfilefunction

tempfile.mkstemp()

temporary files

Securely creates a temporary file and returns a pair (file descriptor, path); you must delete the file yourself.

Syntax

fd, path = tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

It returns a raw OS file descriptor, not a file object: close it with os.close() or wrap it with open(fd), otherwise descriptors leak. The file is never deleted automatically, so call os.remove(path) in a finally block. Creation is atomic (O_EXCL), which makes it the safe replacement for the deprecated mktemp().

Examples

import os, tempfile
fd, path = tempfile.mkstemp(suffix='.csv', dir='.')
try:
    with open(fd, 'w', encoding='utf-8') as f:  # закроет и дескриптор
        f.write('a,b')
    print(type(fd).__name__, path.endswith('.csv'))  # → int True
finally:
    os.remove(path)
print(os.path.exists(path))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy