Python Glossary Русский

all Python 3Files & I/Ofunction

io.IOBase.flush()

buffer

Forces the internal write buffer out to the file or stream. Useful when the data has to be written right away.

Syntax

file.flush()

Closing a file (including leaving a with block) flushes it for you, so an explicit flush() is rarely needed — mostly in long-running processes where someone else has to see the data now: a live log, or a file another program is reading. Also note that flush() hands the bytes to the operating system, not necessarily to the physical disk; if the data must survive a power loss, follow it with os.fsync(file.fileno()).

Examples

import sys
# немедленный вывод без буферизации
print('загрузка...', end='', flush=True)
import os, sys
# или явно:
sys.stdout.write('статус')
sys.stdout.flush()
with open('log.txt', 'w') as f:
    f.write('событие')
    f.flush()  # данные отданы ОС, но ещё не обязательно на диске
    os.fsync(f.fileno())  # а вот теперь — на диске

See also

Open in the full glossarydocs.python.orgReport an inaccuracy