我在 python 中遇到一个奇怪的错误。当我尝试使用 zip 模块提取受密码保护的文件时,尝试将“oy”设置为密码时出现异常。其他一切似乎都有效。ZipFile 模块中的错误?
import zipfile
zip = zipfile.ZipFile("file.zip", "r")
zip.setpassword("oy".encode('utf-8'))
zip.extractall() #Above password "oy" generates the error here
zip.close()
这是我得到的例外:
Traceback (most recent call last):
File "unzip.py", line 4, in <module>
zip.extractall()
File "C:\Program Files\Python32\lib\zipfile.py", line 1002, in extrac
l
self.extract(zipinfo, path, pwd)
File "C:\Program Files\Python32\lib\zipfile.py", line 990, in extract
return self._extract_member(member, path, pwd)
File "C:\Program Files\Python32\lib\zipfile.py", line 1035, in _extra
member
shutil.copyfileobj(source, target)
File "C:\Program Files\Python32\lib\shutil.py", line 65, in copyfileo
buf = fsrc.read(length)
File "C:\Program Files\Python32\lib\zipfile.py", line 581, in read
data = self.read1(n - len(buf))
File "C:\Program Files\Python32\lib\zipfile.py", line 633, in read1
max(n - len_readbuffer, self.MIN_READ_SIZE)
zlib.error: Error -3 while decompressing: invalid block type
如果我使用 UTF-16 作为编码,我会收到此错误:
zlib.error: Error -3 while decompressing: invalid distance too far back
编辑 我现在已经在虚拟 Linux 机器上测试了以下内容:
- Python版本:2.6.5
- 我创建了一个受密码保护的 zip 文件
zip -e file.zip hello.txt
现在看来问题出在了别的地方。现在,即使密码错误,我也可以提取 zip 文件!
try:
zip.setpassword("ks") # "ks" is wrong password but it still extracts the zip
zip.extractall()
except RuntimeException:
print "wrong!"
有时我可以使用错误的密码提取 zip 文件。然后提取文件(在 zip 文件中),但是当我尝试打开它时,信息似乎已损坏/解密。