There is a code that, when a file is changed, displays in the console an alert that the file has been changed. At the same time, he must additionally write the same alert to the file, but for some reason, everything is fine in the console, but does not write to the file. I can not understand what the problem is, help.

with open('test.txt') as file: buffer = file.read() log_file = open('log.txt', 'w') while True: content = open('test.txt').read() if buffer != content: print('Change!') log_file.write('Change') buffer = content 
  • Add log_file.flush() after log_file.write ... - MaxU
  • @MaxU Worked, can you explain this moment? - Igor Igoryanych

1 answer 1

 log_file.write('Change') 

writes to file using OS. The operating system decides for itself when to flush the buffer to disk, so most likely nothing will immediately appear in the disk file.

 log_file.flush() 

gives the OS command a "flush" file buffer to disk.

When opening a file, we can control the buffering with the open(..., buffering=...) parameter open(..., buffering=...) :

If you want to see the size of the file, it will be the size of the bag. It is a line that can be used for the system. If omitted, the system default is used.

from python 3.6 docks:

is used to set the buffering policy. Pass 0 to switch it off (only allowed in binary mode), 1 to select a line-up chunk buffer. When no buffering is given, the default buffering policy is as follows:

Binary files are buffered in fixed-size chunks; The size of the buffer is the “block size” and the falling back on io.DEFAULT_BUFFER_SIZE. For many systems, the buffer will be 4096 or 8192 bytes long. “Interactive” text files (files for which isatty () returns True) use line buffering. The text is described below for binary files.

  • It is worth mentioning explicitly that the default files are completely buffered, and when outputting directly to the console, the buffer is cleared after each line. (See the second reason from the pexpect FAQ ) about the origin of this behavior - jfs