示例代码
try:
f = open('D:/_jobs/test1.txt', 'r')
print(f.read())
finally:
if f:
f.close()
报错信息如下:
Traceback (most recent call last):
File "io/open.py", line 2, in <module>
f = open('D:/_jobs/test1.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'D:/_jobs/test1.txt'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "io/open.py", line 5, in <module>
if f:
NameError: name 'f' is not defined
这里f为什么未定义
嗯,正确的写法是
finally的作用是不管有没有错误都要执行的,有错误也要执行的,执行open()操作发送了错误,这个语句并没有被执行完,所以f并没有被定义,但是finally中的操作还是要继续的,自然找不到f。
这是新手一开始就学习解释性语言容易犯的错误
你可以运行上面的代码想想看。
先声明变量是编程时候的好习惯。