【发布时间】:2013-03-07 15:37:15
【问题描述】:
我正在尝试覆盖一个文件。我的回答基于Read and overwrite a file in Python
完成我的代码:
<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'))
我当前代码的输出:
当我再次尝试重写为custom 时,该文件包含cat_desc。它重写为customc。注意末尾的c,它必须是custom。
这是我想要实现的目标:
- 我写在文件上,例如
cat_desc - 如果我想再写,例如
custom,cat_desc必须被删除并替换为custom。
【问题讨论】:
-
错误发生在哪一行?
-
docs.python.org/2/library/re.html#re.subre.sub 接受三个字符串参数“模式”/“替换”、“字符串”。第四个参数(您的“文本”参数)必须是指定计数的数字
-
用
re.sub应该做什么?参数在问题和回溯中的顺序不同! -
@gnibbler 抱歉,我现在正在编辑我的代码,只是为了得到准确的输出
-
@RedBaron 谢谢,我现在更新我的最新答案