当前位置:   article > 正文

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

nameerror: name 'filenotfounderror' is not defined

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


python版本:2.7


python代码:

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

运行结果:

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


报错原因:

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

在python2.7中使用IOError



修改后的python代码

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

运行结果:

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



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/963882
推荐阅读
相关标签
  

闽ICP备14008679号