Popular recipes tagged "atomic"http://code.activestate.com/recipes/tags/atomic/2016-03-23T14:14:26-07:00ActiveState Code RecipesSafely and atomically write to a file (Python)
2016-03-23T14:14:26-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/579097-safely-and-atomically-write-to-a-file/
<p style="color: grey">
Python
recipe 579097
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/atomic/">atomic</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/save/">save</a>).
Revision 3.
</p>
<p>Saving the user's data is risky. If you write to a file directly, and an error occurs during the write, you may corrupt the file and lose the user's data. One approach to prevent this is to write to a temporary file, then only when you know the file has been written successfully, over-write the original. This function returns a context manager which can make this more convenient.</p>
<p>Update: this now uses <code>os.replace</code> when available, and hopefully will work better on Windows.</p>
Context manager to atomically replace a file (Python)
2012-06-17T12:09:49-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/578166-context-manager-to-atomically-replace-a-file/
<p style="color: grey">
Python
recipe 578166
by <a href="/recipes/users/2033964/">Oren Tirosh</a>
(<a href="/recipes/tags/atomic/">atomic</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/replace/">replace</a>).
Revision 3.
</p>
<p>This context manager ensures that a file's content is either replaced atomically with new contents or left unchanged. An exception or other error will not leave it empty or with partial content.</p>