如何在Python中覆盖文件?
我正试图覆盖一个文件。我的回答基于此 要完成我的代码:如何在Python中覆盖文件?,python,file,Python,File,我正试图覆盖一个文件。我的回答基于此 要完成我的代码: <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 ord
<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'))
定制订单
升序
降序
def自动分拣(请求):
sort_by=request.GET.GET('sort_by',None)
如果排序依据:
temp_path=“{0}/file.txt”。格式(settings.SITE_ROOT)
f=打开(临时路径,'r+')
text=f.read()
text=re.sub('cat_asc','cat_desc',text)
f、 搜索(0)
f、 书写(文本)
f、 截断()
f、 close();
句柄=打开(临时路径“w+”)
handle.write(排序依据)
handle.close();
返回HttpResponseRedirect(反向('envelopes:editor'))
当前代码的输出:
当我再次尝试以custom
重写时,该文件包含cat_desc
。它重写为customc
。注意末尾的c
,它必须是custom
以下是我想要实现的目标:
<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'))
cat_desc
custom
,则必须删除cat_desc
,并将其替换为custom
你能复制并粘贴完整的错误吗 尝试: 新安瑟 您正在将
text
作为re.sub
的第四个参数传递。这应该是一个int
Help on function sub in module re:
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used.
旧答案 也许你在做什么
from os import open
这是一个不同的(较低级别)打开,您只需要使用内置打开(不需要导入任何内容即可使用它)
下面是一个出错并收到错误消息的示例
>>> from os import open
>>> open("some_path", "r+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>从操作系统导入打开
>>>打开(“某些路径”,“r+”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:需要一个整数
此外,要覆盖该文件,您需要使用“w+”打开。“r”代表读取您的问题与写入文件无关 回溯告诉您,这条线是罪魁祸首:
File "/home/cath/src/envelopebudget/envelopebudget/settings/../apps/envelopes/views.py" in auto_sort
357. text = re.sub('cat_desc', 'cat_asc', 'custom', text)
如果您查看该方法,您将其称为错误的:
re.sub(pattern, repl, string, count=0, flags=0)
您将'cat_desc'
作为模式传递,'cat_asc'
作为repl
,'custom'
作为字符串
,而文本
作为计数
。那没有任何意义re.sub
要求count
为整数,您已经给它一个字符串。对于您的新问题:
试图就地覆盖一个文件基本上是不可能的,除非您用完全相同长度的新字节字符串替换字节字符串。如果您将'cat\u desc'
替换为'cat\u asc'
,那么最终将得到'cat\u ascc'
你在'r+'
模式下打开它,读取整个内容,处理它,查找到0,然后写入整个内容,这样做确实有效。但这不是最好的做事方式
无论如何,您的问题是,在执行此操作之后,立即以'w+'
模式打开完全相同的路径(该模式会截断文件)并写入不同的内容。所以,你写的东西现在都不见了
解决办法是…不要那样做。我不知道你想做什么,但那可能不是
同时,重写文件的最佳方法是“原子写入临时文件并重命名”习惯用法。这保证了您不会损坏该文件,您可以获得新文件,也可以保留旧文件。这也意味着你不必把整个文件都保存在内存中;你可以一点一点地走。这很简单…如果你不在乎Windows的话。它的工作原理如下:
with tempfile.NamedTemporaryFile(delete=False) as outfile:
with open(inpath) as infile:
# copy from infile to outfile, changing things as you go
os.rename(outfile.name, inpath)
不幸的是,在Windows上工作是非常痛苦的。当输出文件
仍处于打开状态时,您不能移动它,也不能在with
语句之外访问它,更重要的是,您不能用输出文件
覆盖infle
;你必须做一个复杂的洗牌。而且它永远不会是完全原子化的,除非您愿意使用Vista/2008并直接调用Win32 API。根据您修改后的问题,类似这样的东西可能会更简单
def auto_sort(request):
sort_by = request.GET.get('sort_by', None)
if sort_by:
temp_path = "{0}/file.txt".format(settings.SITE_ROOT)
#Set new_text to whatever you want based on your logic
new_text = 'custom'
f=open(temp_path,'w')
f.write(new_text)
f.close();
handle=open(temp_path,'w+')
handle.write(sort_by)
handle.close();
return HttpResponseRedirect(reverse('envelopes:editor'))
错误发生在哪一行?sub接受三个字符串参数'pattern'/'replacement','string'。第四个参数(您的“text”参数)必须是一个指定计数的数字re.sub
行应该做什么?参数在问题和回溯中的顺序不同@对不起,我现在正在编辑我的代码,只是为了得到确切的信息output@RedBaron谢谢,我现在更新我的答案,因为我没有使用os import open的。
@catherine,好的。问题与覆盖文件无关,而是您正在使用的watre.sub
ok我已经删除了自定义项,现在可以使用了。凯瑟琳:好的,但如果这不起作用,你就有一个完全不同的问题,你需要详细地告诉我们那是什么,最好是在一个新问题中。它允许创建新问题吗?我的问题是覆盖作为标题的文件。是的,允许甚至鼓励创建新问题。这些问题和答案应该对未来有类似问题的搜索者有用。如果您在得到答案后立即更改问题,则原始问题将不再存在,并且原始答案将不再适用于该问题。我再次收到错误TypeError:需要整数。这是之前的错误。请删除re子零件。你不需要它