繁体   English   中英

异常后使python代码继续

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM