【问题标题】:How to check if a zip file is encrypted using python's standard library zipfile?如何检查 zip 文件是否使用 python 的标准库 zipfile 加密?
【发布时间】:2012-08-20 13:18:47
【问题描述】:

我正在使用 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 是否已加密?我没有发现可以让这项工作更简单的异常捕获。

【问题讨论】:

    标签: python zip python-2.7 zipfile encryption


    【解决方案1】:

    快速浏览the zipfile.py library code 表明您可以检查 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 然后循环遍历信息列表() 并查看 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....
    

    【讨论】:

    • ** except **,不是 catch。 (+1) 用于查看源代码。
    • 糟糕。每次我从 Java 切换到 Python 或 Python 到 Java 时,我都必须抓住我的捕获和除外。对不起。
    • 我建议的另一件事是将 # RuntimeError for other reasons ... 更改为 raise e #Unknown RuntimeError -- 只是为了证明您可以重新引发已捕获的异常。
    • 它是这样工作的,我认为关键是except RuntimeError, e:
    【解决方案2】:

    如果要捕获异常,可以这样写:

    zf = zipfile.ZipFile(archive_name)
    try:
        if zf.testzip() == None:
            checksum_OK = True
    except RuntimeError:
        pass
    

    【讨论】:

    • 是的,但是RuntimeError不能也被其他类型的错误触发吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多