原文链接:http://blog.csdn.net/waiwai3/article/details/77461276
处理文件不存在使用FileNotFoundError来处理异常
Python版本:2.6
python代码:
- def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) +" words.")
filename = 'alice.txt'
count_words(filename
运行结果:
- Traceback (most recent call last):
File "./count_words.py", line 15, in <module>
count_words(filename)
File "./count_words.py", line 6, in count_words
except FileNotFoundError:
NameError: global name 'FileNotFoundError' is not define
报错原因:
FileNotFoundError为python3使用的文本不存在异常处理方法
在python2.7中使用IOError
修改后的python代码
- #!/usr/bin/env python
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
#except FileNotFoundError:
except IOError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) +" words.")
filename = 'alice.txt'
count_words(filename)
运行结果:
- Sorry, the file alice.txt does not exist