13

我在 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 上得到了一些转储。

4

2 回答 2

15

正确的 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')
于 2011-10-09T17:14:56.047 回答
3

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

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

于 2011-10-09T13:28:39.107 回答