title: How to open (read-write) or create a file with truncation allowed?
body: <p>I want to:</p>
  <ul>
  <li>open a file in read-write mode if it exists;</li>
  <li>create it if it doesn't exist;</li>
  <li>be able to truncate it anytime-anywhere.</li>
  </ul>
  <p><strong>EDIT</strong>: with truncate I mean write until a position and discard the remaining part of the file, if present</p>
  <p>All this atomically (with a single <code>open()</code> call or simulating a single <code>open()</code> call)</p>
  <p>No single open modality seems to apply:</p>
  <ul>
  <li>r : obviously doesn't work;</li>
  <li>r+ : fails if the file doesn't exist;</li>
  <li>w: recreate the file if it exists;</li>
  <li>w+: recreate the file if it exists;</li>
  <li>a: can't read;</li>
  <li>a+: can't truncate.</li>
  </ul>
  <p>Some combinations I tried (rw, rw+, r+w, etc.) seems to not work either. Is it possible?</p>
  <p>Some <a href="http://www.tutorialspoint.com/ruby/ruby_input_output.htm" rel="nofollow noreferrer">doc</a> from Ruby (applies to python too):</p>
  <pre class="lang-none prettyprint-override"><code>r
  Read-only mode. The file pointer is placed at the beginning of the file.
  This is the default mode.
  
  r+
  Read-write mode. The file pointer will be at the beginning of the file.
  
  w
  Write-only mode. Overwrites the file if the file exists. If the file
  does not exist, creates a new file for writing.
  
  w+
  Read-write mode. Overwrites the existing file if the file exists. If the
  file does not exist, creates a new file for reading and writing.
  
  a
  Write-only mode. The file pointer is at the end of the file if the file
  exists. That is, the file is in the append mode. If the file does not exist,
  it creates a new file for writing.
  
  a+
  Read and write mode. The file pointer is at the end of the file if the file
  exists. The file opens in the append mode. If the file does not exist, it
  creates a new file for reading and writing.
  </code></pre>