[英]Make python code continue after exception
我正在嘗試從符合特定條件的文件夾中讀取所有文件。 一旦我提出異常,我的程序崩潰了。 我試圖繼續,即使有一個例外,但它仍然停止執行。
這是我幾秒鍾后得到的。
error <type 'exceptions.IOError'>
這是我的代碼
import os
path = 'Y:\\Files\\'
listing = os.listdir(path)
try:
for infile in listing:
if infile.startswith("ABC"):
fo = open(infile,"r")
for line in fo:
if line.startswith("REVIEW"):
print infile
fo.close()
except:
print "error "+str(IOError)
pass
將您的try/except
結構放在更多內容中。 否則,當您收到錯誤時,它將破壞所有循環。
也許在第一個for循環之后,添加try/except
。 然后,如果出現錯誤,它將繼續下一個文件。
for infile in listing:
try:
if infile.startswith("ABC"):
fo = open(infile,"r")
for line in fo:
if line.startswith("REVIEW"):
print infile
fo.close()
except:
pass
這是一個很好的例子,說明為什么你應該在這里使用with
語句來打開文件。 當您使用open()
打開文件但是捕獲到錯誤時,該文件將永遠保持打開狀態。 現在比永遠好 。
for infile in listing:
try:
if infile.startswith("ABC"):
with open(infile,"r") as fo
for line in fo:
if line.startswith("REVIEW"):
print infile
except:
pass
現在,如果捕獲到錯誤,文件將被關閉,因為這是with
語句的作用。
移動for循環內的try / except。 像:
import os
path = 'C:\\'
listing = os.listdir(path)
for infile in listing:
try:
if infile.startswith("ABC"):
fo = open(infile,"r")
for line in fo:
if line.startswith("REVIEW"):
print infile
fo.close()
except:
print "error "+str(IOError)
你的代碼正在完成你告訴它要做的事情。 當你得到一個例外時,它會跳到這一部分:
except:
print "error "+str(IOError)
pass
由於之后什么也沒有,程序結束。
而且,那個pass
是多余的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.