Python Glossary Русский

all Python 3tempfileterm

tempfile.SpooledTemporaryFile

temporary files

A temporary file that keeps data in memory and spills it to disk only when it grows beyond max_size.

Syntax

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

Without max_size (default 0) there is no limit at all and everything stays in memory; it does not mean 'straight to disk', as many assume. Calling fileno() also forces a rollover, because a descriptor needs a real file. It suits uploads of unknown size: small ones never touch the disk and large ones do not eat memory.

Examples

import tempfile
with tempfile.SpooledTemporaryFile(max_size=1024) as f:
    f.write(b'small')
    f.seek(0)
    print(f.read())  # → b'small'
    f.rollover()  # принудительно перенести данные на диск
    f.seek(0)
    print(f.read())  # → b'small'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy