Error of the wrong number of magicians using the ZipFile module in Python

I am using Python 2.7 for Windows 7 (64 bit). When I try to unzip a zip file using the 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 can extract the file I'm trying to extract, just fine. Here is the code I used to extract the 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) 

This code works great for many other zip files that I created using WinRAR, but myzip.zip

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

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

But it did not help. By running my code with this, I get a few dumps in my shell.

+8
python unzip zipfile
source share
2 answers

Valid ZIP files always have "\ x50 \ x4B \ x03 \ x04" at the beginning. You can check if the ZIP file of the file with this code is valid:

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

It will print the file header so you can check.

UPDATE Strange, testzip () and all other functions work well. Have 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') 
+10
source share

Make sure that you really open the ZIP file, and not, for example, a RAR file with the extension .zip. The correct zip files have a header that was not found in this case.

The zipfile module can only open zip files. WinRAR can also open other formats and probably ignores the file name and looks only at the file itself.

+2
source share

All Articles