Python 中的 ZipFile 模块出现错误的幻数错误 [英] Bad magic number error with ZipFile module in Python

查看:88
本文介绍了Python 中的 ZipFile 模块出现错误的幻数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Python 2.7 on Windows 7 (64 bit). When I try to unzip a zip file with ZipFile module I get the following error:-

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

WinRAR could extract the file I am trying to extract just fine. Here is the code I used to extract files from 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

This code is working fine for many other zip files I created using WinRAR but myzip.zip

我尝试在 Python27\Lib\zipfile.py 中注释以下几行:-

I tried commenting the following lines in Python27\Lib\zipfile.py:-

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

但这并没有真正的帮助.有效地运行我的代码,我在我的 shell 上得到了一些转储.

But this didn't really help. Running my code with this in effect, I get some dump on my shell.

推荐答案

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

Correct ZIP files always have "\x50\x4B\x03\x04" in the beginning. You can test whether file is really ZIP file with this code:

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

它会打印文件头以便您检查.

It will print header of file so you can check.

更新奇怪的是,testzip() 和所有其他功能都运行良好.你试过这样的代码吗?

UPDATE Strange, testzip() and all other functions work good. Had you tried such code?

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

这篇关于Python 中的 ZipFile 模块出现错误的幻数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆