繁体   English   中英

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

[英]Bad magic number error with ZipFile module in Python

我在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但myzip.zip创建的许多其他zip文件

我试着在Python27\\Lib\\zipfile.py评论以下几行: -

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

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

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

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

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

UPDATE Strange,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')

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM