Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come a file doesn't get written until I stop the program?

I'm running a test, and found that the file doesn't actually get written until I control-C to abort the program. Can anyone explain why that would happen?

I expected it to write at the same time, so I could read the file in the middle of the process.

import os from time import sleep  f = open("log.txt", "a+") i = 0 while True:   f.write(str(i))   f.write("\n")   i += 1   sleep(0.1) 
like image 219
Marvin K Avatar asked Mar 22 '12 14:03

Marvin K


People also ask

Why should a program close a file when it is finished using it?

Why should a program close a file when it's finished using it? Closing a file disconnects the program from the file. In some systems, failure to close an output file can cause a loss of data.

Why close file in Python?

You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.

What happens when a file opened for writing does not exist?

When you open a file for writing, if the file does not exist, a new file is created. When you open a file for writing, if the file exists, the existing file is overwritten with the new file.


1 Answers

Writing to disk is slow, so many programs store up writes into large chunks which they write all-at-once. This is called buffering, and Python does it automatically when you open a file.

When you write to the file, you're actually writing to a "buffer" in memory. When it fills up, Python will automatically write it to disk. You can tell it "write everything in the buffer to disk now" with

f.flush() 

This isn't quite the whole story, because the operating system will probably buffer writes as well. You can tell it to write the buffer of the file with

os.fsync(f.fileno()) 

Finally, you can tell Python not to buffer a particular file with open(f, "w", 0) or only to keep a 1-line buffer with open(f,"w", 1). Naturally, this will slow down all operations on that file, because writes are slow.

like image 183
Katriel Avatar answered Sep 22 '22 05:09

Katriel