1. 程式人生 > >NameError: name 'FileNotFoundError' is not defined的解決方案

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

處理檔案不存在使用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