Python Glossary Русский

all Python 3Files & I/Oterm

buffering=

open() parameters

The open() parameter that sets the buffering policy: 0 — unbuffered (binary mode only), 1 — line buffered, >1 — the buffer size in bytes, -1 — the system default.

Syntax

open(file, mode='r', buffering=-1)

Until the buffer fills up the data sits in memory, not in the file: if another program is tailing the log, or the process dies, the latest lines are simply not there — only flush() or close() (including leaving a with block) push them out. buffering=1 exists for exactly that live-log case, but it applies to text mode only: in binary mode Python warns and falls back to the normal buffer size.

Examples

# без буфера — только в бинарном режиме
with open('raw.bin', 'wb', buffering=0) as f:
    f.write(b'\x00\x01')
# построчная буферизация — только в текстовом режиме
with open('out.txt', 'w', buffering=1) as f:
    f.write('строка\n')   # уходит на диск на каждом переводе строки
# буфер 4096 байт
with open('out.txt', 'r', buffering=4096) as f:
    print(f.read().strip())  # → строка
open('out.txt', 'w', buffering=0)  # → ValueError: текст без буфера не бывает

See also

Open in the full glossarydocs.python.orgReport an inaccuracy