我在python中有如下代码。我使用'with'关键字打开文件并解析它的内容。但是当我试图关闭文件时会发生错误。请帮助。
错误消息:“NameError:名称'f'未定义”
try:
user_xml_name = raw_input('Enter the xml name: ')
xml_name = user_xml_name.replace(" ", "")
with open(xml_name) as f:
with open("temp_" + xml_name, "w") as f1:
for line in f:
f1.write(line)
except IOError:
print print "File" + " " + user_xml_name + " " + "doesn't exist"
finally :
f.close()
f1.close()
答案 0 :(得分:3)
您无需手动关闭它。 with
声明会照顾它。
所以,删除finally
子句:
try:
user_xml_name = raw_input('Enter the xml name: ')
xml_name = user_xml_name.replace(" ", "")
with open(xml_name) as f:
with open("temp_" + xml_name, "w") as f1:
for line in f:
f1.write(line)
except IOError:
print "File %s doesn't exist",user_xml_name
答案 1 :(得分:0)
以下摘录自“ Head First Python ”:
“ with 语句与文件一起使用时,可以大大减少您必须编写的代码量,因为它无需包含 最终 套件,用于处理可能已打开的数据文件的关闭。 当您使用 时,您不再需要担心关闭所有打开的文件,因为python解释器会为您处理此事。“