python中FileNotFoundError的異常
1、Python無(wú)法讀取不存在的文件,因此它引發(fā)一個(gè)異常:
Traceback(mostrecentcalllast):
File"alice.py",line3,in
withopen(filename)asf_obj:
FileNotFoundError:[Errno2]Nosuchfileordirectory:'alice.txt'
在上述traceback中,最后一行報(bào)告了FileNotFoundError異常,這是Python找不到要打開(kāi)的文件時(shí)創(chuàng)建的異常。在這個(gè)示例中,這個(gè)錯(cuò)誤是函數(shù)open()導(dǎo)致的,因此要處理這個(gè)錯(cuò)誤,必須將try語(yǔ)句放在包含open()的代碼行之前:
filename='alice.txt'
try:
withopen(filename)asf_obj:
contents=f_obj.read()
exceptFileNotFoundError:
msg="Sorry,thefile"+filename+"doesnotexist."
print(msg)
2、try代碼塊引發(fā)FileNotFoundError異常,因此Python找出與該錯(cuò)誤匹配的except代碼塊,并運(yùn)行其中的代碼。最終的結(jié)果是顯示一條友好的錯(cuò)誤消息,而不是traceback:
Sorry,thefilealice.txtdoesnotexist.
以上就是python中FileNotFoundError異常的介紹,希望能對(duì)大家有所幫助。更多Python學(xué)習(xí)教程請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。