Python中的ZipFile模块出现错误的幻数错误

时间:2011-10-09 12:55:33

标签: python unzip python-2.7 zipfile

我在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"

但这并没有真正帮助。运行我的代码实际上,我在我的shell上获得了一些转储。

2 个答案:

答案 0 :(得分:10)

正确的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')

答案 1 :(得分:2)

确保您确实打开了ZIP文件,而不是例如以.zip扩展名命名的RAR文件。正确的zip文件有一个标题,在这种情况下找不到。

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