赞
踩
处理文件不存在使用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 defined
-
- Process 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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。