title: How to overwrite a file in Python?
body: <p>I'm trying to overwrite a file. I based my answer on this <a href="https://stackoverflow.com/questions/2424000/read-and-overwrite-a-file-in-python">Read and overwrite a file in Python</a></p>
  
  <p><strong>To complete my codes:</strong></p>
  
  <pre><code>&lt;select class="select compact expandable-list check-list" 
      ONCHANGE="location = this.options[this.selectedIndex].value;"&gt;
      &lt;option value="{% url envelopes:auto_sort %}?sort_by=custom"&gt;
          Custom order
      &lt;/option&gt;
      &lt;optgroup label="Category"&gt;
          &lt;option value="{% url envelopes:auto_sort %}?sort_by=cat_asc"&gt;
              Ascending order
          &lt;/option&gt;
          &lt;option value="{% url envelopes:auto_sort %}?sort_by=cat_desc"&gt;
              Descending order
          &lt;/option&gt;
      &lt;/optgroup&gt;
  &lt;/select&gt;
  
  def auto_sort(request):
      sort_by = request.GET.get('sort_by', None)
      if sort_by:
          temp_path = "{0}/file.txt".format(settings.SITE_ROOT) 
  
          f=open(temp_path,'r+')
          text = f.read()
          text = re.sub('cat_asc', 'cat_desc', text)
          f.seek(0)
          f.write(text)
          f.truncate()
          f.close();
  
          handle=open(temp_path,'w+')
          handle.write(sort_by)
          handle.close();
  
      return HttpResponseRedirect(reverse('envelopes:editor'))
  </code></pre>
  
  <p>The output of my current codes:</p>
  
  <p>The file contains <code>cat_desc</code> when I try rewrite again as <code>custom</code>. It rewrites as <code>customc</code>. Notice the <code>c</code> at the end, it must be <code>custom</code> only.</p>
  
  <p><strong>Here is what I'm trying to achieve:</strong></p>
  
  <ol>
  <li>I write on file, for example, <code>cat_desc</code></li>
  <li>If I want to write again, for example <code>custom</code>, the <code>cat_desc</code> must be removed and replaced with <code>custom</code>.</li>
  </ol>