Python中的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"
但这并没有真正解决问题。运行我的代码后,终端上出现了一些错误信息。
2 个回答
3
确保你打开的真的是一个ZIP文件,而不是一个后缀名为.zip的RAR文件。真正的ZIP文件有一个特定的开头部分,但在这个情况下没有找到。
zipfile
模块只能打开ZIP文件。WinRAR可以打开其他格式的文件,它可能会忽略文件名,只关注文件的内容。
17
正确的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')