简体   繁体   English

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

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

I am using Python 2.7 on Windows 7 (64 bit). 我在Windows 7(64位)上使用Python 2.7。 When I try to unzip a zip file with ZipFile module I get the following error:- 当我尝试用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 could extract the file I am trying to extract just fine. WinRAR可以提取我试图提取的文件。 Here is the code I used to extract files from myzip.zip 这是我用来从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)

This code is working fine for many other zip files I created using WinRAR but myzip.zip 这段代码适用于我使用WinRAR但myzip.zip创建的许多其他zip文件

I tried commenting the following lines in Python27\\Lib\\zipfile.py :- 我试着在Python27\\Lib\\zipfile.py评论以下几行: -

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

But this didn't really help. 但这并没有真正帮助。 Running my code with this in effect, I get some dump on my shell. 运行我的代码实际上,我在我的shell上得到一些转储。

Correct ZIP files always have "\\x50\\x4B\\x03\\x04" in the beginning. 正确的ZIP文件在开头总是有“\\ x50 \\ x4B \\ x03 \\ x04”。 You can test whether file is really ZIP file with this code: 您可以使用以下代码测试文件是否真的是ZIP文件:

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

It will print header of file so you can check. 它将打印文件头,以便您检查。

UPDATE Strange, testzip() and all other functions work good. UPDATE Strange,testzip()和所有其他函数都运行良好。 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')

Make sure you are really opening a ZIP file, not for example a RAR file named with a .zip extension. 确保您确实打开了ZIP文件,而不是例如以.zip扩展名命名的RAR文件。 Proper zip files have a header, which was not found in this case. 正确的zip文件有一个标题,在这种情况下找不到。

The zipfile module can only open zip files. zipfile模块只能打开zip文件。 WinRAR can also open other formats, and it likely ignores the filename and only looks at the file itself. WinRAR也可以打开其他格式,它可能会忽略文件名,只查看文件本身。

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

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