title: Open file for read/write, create if needed
body: <p>What is the most elegant way to open a file such that</p>
  
  <ul>
  <li>the file gets created if it does not exist,</li>
  <li>the file won't be truncated if it does exist and</li>
  <li>it is possible to write any part of the file (after seeking), not just the end?</li>
  </ul>
  
  <p>As far as I can tell, <a href="http://docs.python.org/3/library/functions.html#open" rel="noreferrer">the <code>open</code> builtin</a> doesn't seem up to the task: it provides various modes, but every one I tried fails to satisfy at least one of my requirements:</p>
  
  <ul>
  <li><code>r+</code> fails if the file does not exist.</li>
  <li><code>w+</code> will truncate the file, losing any existing content.</li>
  <li><code>a+</code> will force all writes to go to the end of the file, at least on my OS X.</li>
  </ul>
  
  <p>Checking for the existence prior to opening the file feels bad since it leaves room for race conditions. The same holds for retrying the open with a different mode from within an exception handler. I hope there is a better way.</p>