How to overwrite a file in Python?
<p>I'm trying to overwrite a file. I based my answer on this <a href="http://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 rewrite as <code>customc</code>. Notice the <code>c</code> in the last, it must be <code>custom</code> only.</p>

<p><strong>Here are what I'm trying to achieve:</strong></p>

<ol>
<li>I write on file. For example, "cat_desc"</li>
<li>If I want to write again, for example "custom". The "cat_desc" must be remove and replace with "custom".</li>
</ol>
