使python代码在异常后继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18994334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make python code continue after exception
提问by Ank
I'm trying to read all files from a folder that matches a certain criteria. My program crashes once I have an exception raised. I am trying to continue even if there's an exception but it still stops executing.
我正在尝试从符合特定条件的文件夹中读取所有文件。一旦我引发异常,我的程序就会崩溃。即使有异常,我也试图继续,但它仍然停止执行。
This is what I get after a couple of seconds.
这是我几秒钟后得到的。
error <type 'exceptions.IOError'>
Here's my code
这是我的代码
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
采纳答案by TerryA
Put your try/except
structure more in-wards. Otherwise when you get an error, it will break all the loops.
把你的try/except
结构更向内。否则,当您遇到错误时,它将中断所有循环。
Perhaps after the first for-loop, add the try/except
. Then if an error is raised, it will continue with the next file.
也许在第一个 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
This is a perfect example of why you should use a with
statement here to open files. When you open the file using open()
, but an error is catched, the file will remain open forever. Now is better than never.
这是为什么您应该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
Now if an error is caught, the file will be closed, as that is what the with
statement does.
现在,如果捕获到错误,文件将被关闭,因为这就是with
语句的作用。
回答by Brendan Long
You're code is doing exactly what you're telling it to do. When you get an exception, it jumps down to this section:
你的代码正在做你告诉它做的事情。当您遇到异常时,它会跳到此部分:
except:
print "error "+str(IOError)
pass
Since there's nothing after that, the program ends.
由于之后没有任何事情,程序结束。
Also, that pass
is superfluous.
还有,那pass
是多余的。
回答by Rami
Move the try/except inside the for loop. Like in:
在 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)