Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does writing a file to disk with Python open().write() ensure the data is available to other processes?

One Python process writes status updates to a file for other processes to read. In some circumstances, the status updates happen repeatedly and quickly in a loop. The easiest and fastest approach is to use to open().write() in one line:

open(statusfile,'w').write(status) 

An alternate approach with four lines that force the data to disk. This has a significant performance penalty:

f = open(self.statusfile,'w')

f.write(status)

os.fsync(f)

f.close()

I'm not trying to protect from an OS crash. So, does the approach force the data to the OS buffer so other processes read the newest status data when they open the file from disk? Or, do I need to use os.fsync()?

like image 506
tahoar Avatar asked Oct 31 '11 15:10

tahoar


People also ask

What happens if you open a file for writing and it already exists Python?

OK, but what happens when you try to open a file for writing using a filename that already exists? Nothing, error-wise. But whatever file that existing filename pointed to is basically wiped out. You may get an error message if you attempt to write to a path that points to a directory or some kind of protected file.

Are both reading and writing possible after opening a file in Python?

Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s).

What does writing a file mean in Python?

Definition and Usage The write() method writes a specified text to the file.

What happens if you open a file for reading and it doesn't exist Python?

The read mode in Python opens an existing file for reading, positioning the pointer at the file's start. Note: If the file does not exist, Python throws an error. In all cases, the function returns a file object and the characteristics depend on the chosen mode.


1 Answers

No, the first approach does not guarantee that the data is written out, since it is not guaranteed that the file will be flushed and closed once the handle is no longer referenced by its write member. This is likely the case with CPython, but not necessarily with other Python interpreters; it's an implementation detail of the Python garbage collector.

You should really use the second approach, except that os.fsync is not needed; just close the file and the data should be available to other processes.

Or, even better (Python >=2.5):

with open(self.statusfile, 'w') as f:
    f.write(status)

The with version is exception-safe: the file is closed even if write fails.

like image 71
Fred Foo Avatar answered Sep 24 '22 19:09

Fred Foo