title: How do I handle errors when overwriting an existing file in python
body: <p>When I try to write to a file that already exists, but the write fails, the file gets overwritten with nothing (i.e. it gets cleared - contents of the existing file are deleted).</p>
  <p>Example:</p>
  <pre class="lang-sh prettyprint-override"><code>alaa@vernal:~/Test$ echo &quot;sometext&quot; &gt; testfile
  alaa@vernal:~/Test$ cat testfile 
  sometext
  </code></pre>
  <p>In Python:</p>
  <pre class="lang-py prettyprint-override"><code>with open('testfile', 'w') as f:
      f.write(doesntexist)
  
  Traceback (most recent call last):
    File &quot;&lt;stdin&gt;&quot;, line 2, in &lt;module&gt;
  NameError: name 'doesntexist' is not defined
  </code></pre>
  <p>The file is empty:</p>
  <pre class="lang-sh prettyprint-override"><code>alaa@vernal:~/Test$ cat testfile 
  alaa@vernal:~/Test$
  </code></pre>
  <p>I tried to handle the exception like this but it still empties the file:</p>
  <pre class="lang-py prettyprint-override"><code>import traceback
  
  with open('testfile', 'w') as f:
      try:
          f.write(doesntexist)
          print('OK')
      except:
          print('NOT OK')
          traceback.print_exc()
  
  NOT OK
  Traceback (most recent call last):
    File &quot;&lt;stdin&gt;&quot;, line 3, in &lt;module&gt;
  NameError: name 'doesntexist' is not defined
  </code></pre>
  <p>I tried handling it in a different way, but it still empties the file:</p>
  <pre class="lang-py prettyprint-override"><code>import traceback
  
  try:
      with open('testfile', 'w') as f:
          f.write(doesntexist)
          print('OK')
  except:
      print('NOT OK')
      traceback.print_exc()
  
  NOT OK
  Traceback (most recent call last):
    File &quot;&lt;stdin&gt;&quot;, line 3, in &lt;module&gt;
  NameError: name 'doesntexist' is not defined
  </code></pre>
  <p>I feel like I'm missing something. Is there a straight forward way of handling this situation in Python to <em>not</em> clear the file if the write fails for any reason? Or do I have to resort to 'cleverer' code, for example: read the contents of the file first, and if the write fails, write it back again with the original contents, or maybe attempt to write the data to a temp file first, etc.?</p>