如何使用Python标准库zipfile检查zip文件是否已加密?

12

我正在使用Python标准库zipfile来测试一个压缩文件:

zf = zipfile.ZipFile(archive_name)
if zf.testzip()==None: checksum_OK=True

我遇到了这个运行时异常:

File "./packaging.py", line 36, in test_wgt
    if zf.testzip()==None: checksum_OK=True
  File "/usr/lib/python2.7/zipfile.py", line 844, in testzip
    f = self.open(zinfo.filename, "r")
  File "/usr/lib/python2.7/zipfile.py", line 915, in open
    "password required for extraction" % name
RuntimeError: File xxxxx/xxxxxxxx.xxx is encrypted, password required for extraction

在运行testzip()之前,我如何测试zip文件是否已加密?我没有发现可以使这项工作更简单的异常可供捕获。

2个回答

17

快速查看zipfile.py库代码可以发现,您可以检查ZipInfo类的flag_bits属性以查看文件是否已加密,如下所示:

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

检查0x1位是否设置是zipfile.py源码用来判断文件是否加密的方法(文档可能需要改进!)你可以尝试捕获testzip()中的RuntimeError,然后循环infolist()并查看zip文件中是否有加密文件。

你也可以直接这么做:

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....

2
不是catch,而是except。如果查看源代码会得到额外的1分。 - mgilson
糟糕了,每次我从Java切换到Python或从Python切换到Java时,我都必须捕捉我的catch和except。抱歉。 - Zachary Hamm
4
我建议的另一件事是将#RuntimeError for other reasons...改为raise e#未知RuntimeError-- 这只是为了演示您可以重新引发您捕获的异常。 - mgilson
它的工作方式是这样的,我认为关键在于 except RuntimeError, e: - Eduard Florinescu

0
如果您想捕获异常,可以编写以下代码:
zf = zipfile.ZipFile(archive_name)
try:
    if zf.testzip() == None:
        checksum_OK = True
except RuntimeError:
    pass

2
是的,但RuntimeError是否也可能由其他类型的错误触发? - Eduard Florinescu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接