Python cant handle exceptions from zipfile.BadZipFile

微笑、不失礼 提交于 2019-12-08 08:14:39

问题


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

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

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


回答1:


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 "

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.



来源:https://stackoverflow.com/questions/39154470/python-cant-handle-exceptions-from-zipfile-badzipfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!