Python Glossary Русский

all Python 3tempfilefunction

tempfile.TemporaryFile()

temporary files

Creates an anonymous temporary file opened for reading and writing; it is deleted automatically when closed.

Syntax

tempfile.TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)

The default mode is 'w+b', so write('text') fails with TypeError: pass mode='w+' and encoding='utf-8' for strings. After writing, the file position is at the end and read() returns nothing until you call seek(0). On Linux the file has no name at all (name is an integer file descriptor), so you cannot hand its path to another program; use NamedTemporaryFile for that.

Examples

import tempfile
with tempfile.TemporaryFile(mode='w+', encoding='utf-8') as f:
    f.write('привет')
    print(repr(f.read()))  # → '' — указатель в конце файла
    f.seek(0)
    print(f.read())  # → привет
import tempfile
with tempfile.TemporaryFile() as f:
    print(type(f.name).__name__)  # → ? int на Linux, str на Windows

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy