How to safely maintain a status file

Richard Baron Penman richardbp at
Sun Jul 8 13:29:41 CEST 2012


I want my script to generate a ~1KB status file several times a second.
The script may be terminated at any time but the status file must not
be corrupted.
When the script is started next time the status file will be read to
check what needs to be done.

My initial solution was a thread that writes status to a tmp file
first and then renames:

open(tmp_file, 'w').write(status)
os.rename(tmp_file, status_file)

This works well on Linux but Windows raises an error when status_file
already exists.

I guess I could delete the status file:

open(tmp_file, 'w').write(status)
if os.path.exists(status_file):
os.rename(tmp_file, status_file)

and then on startup read from tmp_file if status_file does not exist.
But this seems awkward.

Is there a better way? Or do I need to use a database?


More information about the Python-list mailing list