title: How to safely write to a file?
body: <p>Imagine you have a library for working with some sort of XML file or configuration file. The library reads the whole file into memory and provides methods for editing the content. When you are done manipulating the content you can call a <code>write</code> to save the content back to file. The question is how to do this in a safe way.</p>
  
  <p>Overwriting the existing file (starting to write to the original file) is obviously not safe. If the <code>write</code> method fails before it is done you end up with a half written file and you have lost data.</p>
  
  <p>A better option would be to write to a <strong>temporary</strong> file somewhere, and when the <code>write</code> method has finished, you <strong>copy</strong> the temporary file to the original file.</p>
  
  <p>Now, if the copy somehow fails, you still have correctly saved data in the temporary file. And if the copy succeeds, you can remove the temporary file.</p>
  
  <p>On POSIX systems I guess you can use the <code>rename</code> system call which is an atomic operation. But how would you do this best on a Windows system? In particular, how do you handle this best using <strong>Python</strong>?</p>
  
  <p>Also, is there another scheme for safely writing to files?</p>