gpt4 book ai didi

python - NameError 使用 "finally: f.close()"和 "with open(..) as f"

转载 作者:行者123 更新时间:2023-11-28 16:36:01 25 4
gpt4 key购买 nike

我在 python 中有如下代码。我正在使用“with”关键字打开一个文件并解析它的内容。但是当我试图关闭文件时发生错误。请帮助。

错误信息:“NameError:name 'f' is not defined”

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()

最佳答案

您不需要手动关闭它。 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

关于python - NameError 使用 "finally: f.close()"和 "with open(..) as f",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26071836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com