title: How to create file if it does not exists, if exists then don't truncate - Python27
body: <p>I have this code </p>
  
  <pre><code> with codecs.open("file.json", mode='a+', encoding='utf-8') as f:
  </code></pre>
  
  <p>I want:</p>
  
  <p>1) Create file if it does not exists, and start writing from the start of file.</p>
  
  <p>2) If exists, first read it and truncate it and then write something.</p>
  
  <p>I found this somewhere</p>
  
  <pre><code> ``r''   Open text file for reading.  The stream is positioned at the
           beginning of the file.
  
   ``r+''  Open for reading and writing.  The stream is positioned at the
           beginning of the file.
  
   ``w''   Truncate file to zero length or create text file for writing.
           The stream is positioned at the beginning of the file.
  
   ``w+''  Open for reading and writing.  The file is created if it does not
           exist, otherwise it is truncated.  The stream is positioned at
           the beginning of the file.
  
   ``a''   Open for writing.  The file is created if it does not exist.  The
           stream is positioned at the end of the file.  Subsequent writes
           to the file will always end up at the then current end of file,
           irrespective of any intervening fseek(3) or similar.
  
   ``a+''  Open for reading and writing.  The file is created if it does not
           exist.  The stream is positioned at the end of the file.  Subse-
           quent writes to the file will always end up at the then current
           end of file, irrespective of any intervening fseek(3) or similar.
  </code></pre>
  
  <p><code>a+</code> mode suits me best but what it does that it only lets me write at end of file, </p>
  
  <p>With <code>a+</code> mode I have this <code>f.seek(0)</code> immediately after opening file, but it has no affect, it does not seek to the start of file.</p>