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:-
JavaScript
x
11
11
1
Traceback (most recent call last):
2
File "unzip.py", line 8, in <module>
3
z.extract(name)
4
File "C:Python27libzipfile.py", line 950, in extract
5
return self._extract_member(member, path, pwd)
6
File "C:Python27libzipfile.py", line 993, in _extract_member
7
source = self.open(member, pwd=pwd)
8
File "C:Python27libzipfile.py", line 897, in open
9
raise BadZipfile, "Bad magic number for file header"
10
zipfile.BadZipfile: Bad magic number for file header
11
WinRAR could extract the file I am trying to extract just fine.
Here is the code I used to extract files from myzip.zip
JavaScript
1
5
1
from zipfile import ZipFile
2
z = ZipFile('myzip.zip') //myzip.zip contains just one file, a password protected pdf
3
for name in z.namelist():
4
z.extract(name)
5
This code is working fine for many other zip files I created using WinRAR but myzip.zip
I tried commenting the following lines in Python27Libzipfile.py
:-
JavaScript
1
3
1
if fheader[0:4] != stringFileHeader:
2
raise BadZipfile, "Bad magic number for file header"
3
But this didn’t really help. Running my code with this in effect, I get some dump on my shell.
Advertisement
Answer
Correct ZIP files always have “x50x4Bx03x04” in the beginning. You can test whether file is really ZIP file with this code:
JavaScript
1
3
1
with open('/path/to/file', 'rb') as MyZip:
2
print(MyZip.read(4))
3
It will print header of file so you can check.
UPDATE Strange, testzip() and all other functions work good. Had you tried such code?
JavaScript
1
4
1
with zipfile.GzipFile('/path/to/file') as Zip:
2
for ZipMember in Zip.infolist():
3
Zip.extract(ZipMember, path='/dir/where/to/extract', pwd='your-password')
4