NameError: name 'FileNotFoundError' is not defined的解决方案

来源:互联网 发布:super kamagra 淘宝 编辑:程序博客网 时间:2024/06/05 16:33

处理文件不存在使用FileNotFoundError来处理异常


python版本:2.7


python代码:

filename='waiwai.txt'try:with open(filename) as f_obj:contents=f_obj.read()except FileNotFoundError:print "Sorry,the file does't exist."

运行结果:

Traceback (most recent call last):  File "J:/Python/821_03.py", line 5, in <module>    except FileNotFoundError:NameError: name 'FileNotFoundError' is not definedProcess finished with exit code 1


报错原因:

FileNotFoundError为python3使用的文本不存在异常处理方法

在python2.7中使用IOError



修改后的python代码

filename='waiwai.txt'try:with open(filename) as f_obj:contents=f_obj.read()except IOError:print "Sorry,the file does't exist."

运行结果:

Sorry,the file does't exist.Process finished with exit code 0



原创粉丝点击