我正在学习python,但遇到了一些错误。
下面是我的代码:
try:
a=open("doesnotexist.txt")
content=a.read()
print(content)
except FileNotFoundError as e:
print(e)
finally:
a.close()结果如下:
[Errno 2] No such file or directory: 'doesnotexist.txt'
Traceback (most recent call last):
File "e:/python learning/exhandling1.py", line 8, in <module>
a.close()
NameError: name 'a' is not defined发布于 2020-06-14 02:59:55
因为open()函数抛出了一个异常,变量a没有被赋值。然后,在finally块中,您尝试调用a的方法,这是不可能的,因为没有定义a。
通常,在打开文件时,您应该使用with statement。
例如:
try:
with open('doesnotexist.txt', 'r') as opened_file:
content = opened_file.read()
print(content)
except FileNotFoundError:
print('no file found')https://stackoverflow.com/questions/62364217
复制相似问题