这是我用来创建用于导入XML文件的函数的代码。我相信这应该可以,但是出现错误
import xml.etree.ElementTree as ET
xmlfile = 'aniaml.xml'
try :
xmldata= open(xmlfile, 'r')
xmltree = ET.fromstring(xmldata.read())
except FileNotFoundError:
print('Could not open the file:'.format(xmlfile))
finally:
xmldata.close()
`
错误是
NameError Traceback (most recent call last)
<ipython-input-6-0edd7906a4b0> in <module>
11 print('Could not read from the file:'.format(xmlfile))
12 finally :
---> 13 xmldata.close()
NameError: name 'xmldata' is not defined
有人可以帮忙吗?
答案 0 :(得分:0)
如果未找到文件,则无需关闭它,并且在分配和定义xmldata
变量之前引发了异常。
如果您遇到其他错误,请注意在该位置关闭文件或捕获另一个异常。
答案 1 :(得分:0)
尝试一下,
id time event x y z
T1 1500 stopped 100 100 120
T2 1200 travelling 100 200 120
答案 2 :(得分:0)
您正在代码的try
部分中使用xmldata,并在finally
中关闭文件,如果找不到文件,则不会定义xmldata变量,但是您再次在{{1}中关闭xmldata }这就是您收到错误的原因。
您可以使用
finally
try:
with open(xmlfile,'r') as f:
# your code
except FileNotFoundError:
# your code for exception.
自动关闭文件,无需担心。除非您想捕获其他异常,否则无需进行finally操作。
答案 3 :(得分:0)
由于open()
调用失败,因此从未定义xmldata
。那么如何确保关闭它呢?这正是创建with
语句的目的。这样包裹open
,当且仅当有要关闭的东西时,它才会关闭:
try:
with open(xmlfile, 'r') as xmldata:
xmltree = ET.fromstring(xmldata.read())
except FileNotFoundError:
print("Could not open", xmlfile)
如您所见,关闭文件已委派给“上下文管理器”。您只需要处理异常即可。