How to check if a zip file is encrypted using python's standard library zipfile?

二次信任 提交于 2019-12-05 01:47:23

A quick glance at the zipfile.py library code shows that you can check the ZipInfo class's flag_bits property to see if the file is encrypted, like so:

zf = zipfile.ZipFile(archive_name)
for zinfo in zf.infolist():
    is_encrypted = zinfo.flag_bits & 0x1 
    if is_encrypted:
        print '%s is encrypted!' % zinfo.filename

Checking to see if the 0x1 bit is set is how the zipfile.py source sees if the file is encrypted (could be better documented!) One thing you could do is catch the RuntimeError from testzip() then loop over the infolist() and see if there are encrypted files in the zip.

You could also just do something like this:

try:
    zf.testzip()
except RuntimeError as e:
    if 'encrypted' in str(e):
        print 'Golly, this zip has encrypted files! Try again with a password!'
    else:
        # RuntimeError for other reasons....

If you want to catch an exception, you can write this:

zf = zipfile.ZipFile(archive_name)
try:
    if zf.testzip() == None:
        checksum_OK = True
except RuntimeError:
    pass
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!