这是将python"with"语句与try-except块结合使用的正确方法吗?:
try:
with open("file", "r") as f:
line = f.readline()
except IOError:
<whatever>
Run Code Online (Sandbox Code Playgroud)
如果是,那么考虑旧的做事方式:
try:
f = open("file", "r")
line = f.readline()
except IOError:
<whatever>
finally:
f.close()
Run Code Online (Sandbox Code Playgroud)
这里"with"语句的主要好处是我们可以摆脱三行代码吗?对于这个用例来说,这似乎并不令我感到高兴(尽管我理解"with"语句还有其他用途).
编辑:上面两个代码块的功能是否相同?
EDIT2:前几个答案一般性地讨论了使用"with"的好处,但这些似乎在边缘效益.我们已经(或应该已经)多年来明确地调用f.close().我想一个好处是,草率编码器将从使用"with"中受益.
我有以下代码:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
Run Code Online (Sandbox Code Playgroud)
我想用新内容替换文件中的旧内容.但是,当我执行我的代码时,附加了文件"test.xml",即我将旧的内容与新的"替换"内容相对应.我该怎么做才能删除旧的东西,只保留新的东西?
我正在尝试覆盖文件.我的回答基于这个Read并用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'))
Run Code Online (Sandbox Code Playgroud)
我当前代码的输出:
cat_desc当我再次尝试重写时,该文件包含custom.它重写为customc.注意c最后,它必须是custom唯一的.
这是我想要实现的目标: …
我有线
for line in fileinput.input(file_full_path, inplace=True):
newline, count = re.subn(search_str, replace_str, line.rstrip())
# ... display some messages to console ...
print newline # this is sent to the file_full_path
Run Code Online (Sandbox Code Playgroud)
应该替换search_str文件中所有出现的内容,file_full_path并用替换它们replace_str。该fileinput映射stdout到指定的文件。因此,print newline发送到的内容sys.stdout将发送到文件而不是控制台。
在此过程的中间,我想向控制台显示一些消息,例如,我可以显示将要发生替换的那部分行或其他消息,然后继续操作print newline到文件中。这该怎么做?