Python中ZipFile模块出现Bad magic number错误

14

我正在使用 Windows 7(64位)上的 Python 2.7。当我尝试使用 ZipFile 模块解压缩 zip 文件时,会出现以下错误:

Traceback (most recent call last):
  File "unzip.py", line 8, in <module>
    z.extract(name)
  File "C:\Python27\lib\zipfile.py", line 950, in extract
    return self._extract_member(member, path, pwd)
  File "C:\Python27\lib\zipfile.py", line 993, in _extract_member
    source = self.open(member, pwd=pwd)
  File "C:\Python27\lib\zipfile.py", line 897, in open
    raise BadZipfile, "Bad magic number for file header"
zipfile.BadZipfile: Bad magic number for file header

WinRAR可以很好地提取我正在尝试提取的文件。 这是我用来从myzip.zip解压缩文件的代码。

from zipfile import ZipFile
z = ZipFile('myzip.zip')   //myzip.zip contains just one file, a password protected pdf        
for name in z.namelist():
    z.extract(name)

这段代码在我使用WinRAR创建的许多其他zip文件中运行良好,但无法解压myzip.zip

我尝试注释掉以下几行在Python27\Lib\zipfile.py中的代码:

if fheader[0:4] != stringFileHeader:
   raise BadZipfile, "Bad magic number for file header"

但这并没有真正帮助。使用此代码后,在我的终端上会得到一些转储信息。

2个回答

16

正确的ZIP文件开头总是有“\x50\x4B\x03\x04”。您可以使用以下代码测试文件是否真正为ZIP文件:

with open('/path/to/file', 'rb') as MyZip:
  print(MyZip.read(4))

它会打印文件头,以便您可以检查。

更新 奇怪的是,testzip() 和所有其他函数都工作良好。你尝试过这样的代码吗?

with zipfile.GzipFile('/path/to/file') as Zip:
  for ZipMember in Zip.infolist():
    Zip.extract(ZipMember, path='/dir/where/to/extract', pwd='your-password')

2
@petr-viktorin 是的,它是一个zip文件。上面的代码输出了PK♥♦ - haltTm
嗯,你能把文件放在任何服务器上,这样我就可以查看并尝试打开它吗? - ghostmansd
看看原来的答案,我发了另一个想法。 - ghostmansd
哦,使用Ark我无法从您的文件中提取pdf。更准确地说,它会提取大小为0 KiB的空文件。 - ghostmansd
7-Zip提示“不支持的压缩方法”。 - John Machin
3
Python的zipfile目前仅支持DEFLATE压缩方法。看起来您使用WinRar使用了其他压缩方法创建了文件,因此zipfile只能读取文件,而无法解压缩。 - ghostmansd

3

请确保您打开的是一个真正的ZIP文件,而不是以.zip扩展名命名的RAR文件等其他格式。真正的ZIP文件有一个头部,在这种情况下未被找到。

zipfile模块只能打开ZIP文件。WinRAR可以打开其他格式,它可能会忽略文件名,只看文件本身。


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