我正在学习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:58:17
无论try-block是否引发异常,都会执行finally。当open()引发FileNotFoundError时,未定义a。您希望改用else,如果try-block未引发异常,则会执行该命令。
但是,使用with-statement更简单,而且不管怎样,它都是最佳实践:
try:
with open("doesnotexist.txt") as a:
content = a.read()
print(content)
except FileNotFoundError as e:
print(e)资料来源:
发布于 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
复制相似问题