I'm trying to overwrite a file. I based my answer on this Read and overwrite a file in Python
To complete my codes:
<select class="select compact expandable-list check-list"
ONCHANGE="location = this.options[this.selectedIndex].value;">
<option value="{% url envelopes:auto_sort %}?sort_by=custom">
Custom order
</option>
<optgroup label="Category">
<option value="{% url envelopes:auto_sort %}?sort_by=cat_asc">
Ascending order
</option>
<option value="{% url envelopes:auto_sort %}?sort_by=cat_desc">
Descending order
</option>
</optgroup>
</select>
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'))
The output of my current codes:
The file contains cat_desc
when I try rewrite again as custom
. It rewrites as customc
. Notice the c
at the end, it must be custom
only.
Here is what I'm trying to achieve:
- I write on file, for example,
cat_desc
- If I want to write again, for example
custom
, thecat_desc
must be removed and replaced withcustom
.