Python无法处理zipfile.BadZipFile中的异常 [英] Python cant handle exceptions from zipfile.BadZipFile

查看:906
本文介绍了Python无法处理zipfile.BadZipFile中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要处理zip文件是否损坏,因此它只需传递此文件即可继续使用下一个文件.

Need to handle if a zip file is corrupt, so it just pass this file and can go on to the next.

在Im试图捕获异常的下面的代码示例中,我可以将其传递.但是,当zip文件损坏时,我的脚本会失败*,并给我正常"的追溯错误*,而不是打印我的错误",但是如果zip文件正常,则脚本运行正常.

In the code example underneath Im trying to catch the exception, so I can pass it. But my script is failing when the zipfile is corrupt*, and give me the "normal" traceback errors* istead of printing "my error", but is running ok if the zipfile is ok.

这是我正在处理的代码的一个简约示例.

This i a minimalistic example of the code I'm dealing with.

path = "path to zipfile" 

from zipfile import ZipFile

with ZipFile(path) as zf:
    try:
        print "zipfile is OK"
    except BadZipfile:
        print "Does not work "
        pass

回溯的一部分告诉我:引发BadZipfile,文件不是zip文件"

part of the traceback is telling me: raise BadZipfile, "File is not a zip file"

推荐答案

您需要将上下文管理器放入 try-except块:

You need to put your context manager inside the try-except block:

try:
    with ZipFile(path) as zf:
        print "zipfile is OK"
except BadZipfile:
    print "Does not work "

错误由引发 ZipFile引发,因此将其放置在外部意味着找不到针对引发的异常的处理程序.另外,请确保从zipfile中适当导入了BadZipFile.

The error is raised by ZipFile so placing it outside means no handler can be found for the raised exception. In addition make sure you appropriately import BadZipFile from zipfile.

这篇关于Python无法处理zipfile.BadZipFile中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆