Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unzipping file results in "BadZipFile: File is not a zip file"

Tags:

python

zipfile

I have two zip files, both of them open well with Windows Explorer and 7-zip.

However when i open them with Python's zipfile module [ zipfile.ZipFile("filex.zip") ], one of them gets opened but the other one gives error "BadZipfile: File is not a zip file".

I've made sure that the latter one is a valid Zip File by opening it with 7-Zip and looking at its properties (says 7Zip.ZIP). When I open the file with a text editor, the first two characters are "PK", showing that it is indeed a zip file.

I'm using Python 2.5 and really don't have any clue how to go about for this. I've tried it both with Windows as well as Ubuntu and problem exists on both platforms.

Update: Traceback from Python 2.5.4 on Windows:

Traceback (most recent call last): File "<module1>", line 5, in <module>     zipfile.ZipFile("c:/temp/test.zip") File "C:\Python25\lib\zipfile.py", line 346, in init     self._GetContents() File "C:\Python25\lib\zipfile.py", line 366, in _GetContents     self._RealGetContents() File "C:\Python25\lib\zipfile.py", line 378, in _RealGetContents     raise BadZipfile, "File is not a zip file" BadZipfile: File is not a zip file 

Basically when the _EndRecData function is called for getting data from End of Central Directory" record, the comment length checkout fails [ endrec[7] == len(comment) ].

The values of locals in the _EndRecData function are as following:

 END_BLOCK: 4096,  comment: '\x00',  data: '\xd6\xf6\x03\x00\x88,N8?<e\xf0q\xa8\x1cwK\x87\x0c(\x82a\xee\xc61N\'1qN\x0b\x16K-\x9d\xd57w\x0f\xa31n\xf3dN\x9e\xb1s\xffu\xd1\.....', (truncated)  endrec: ['PK\x05\x06', 0, 0, 4, 4, 268, 199515, 0],  filesize: 199806L,  fpin: <open file 'c:/temp/test.zip', mode 'rb' at 0x045D4F98>,  start: 4073 
like image 241
sharjeel Avatar asked Jun 21 '10 08:06

sharjeel


People also ask

How do I fix a bad zip file in python?

In short: use 'zip -FF file. zip' to fix the file. It will restore the filelist.

Why is zip file not opening?

Zip files may refuse to open if they are not properly downloaded. Also, incomplete downloads occur when files get stuck due to issues like bad internet connection, inconsistency in network connection, all of which can cause transfer errors, affect your Zip files, and make them unable to open.


1 Answers

files named file can confuse python - try naming it something else. if it STILL wont work, try this code:

def fixBadZipfile(zipFile):    f = open(zipFile, 'r+b')    data = f.read()    pos = data.find('\x50\x4b\x05\x06') # End of central directory signature    if (pos > 0):        self._log("Trancating file at location " + str(pos + 22)+ ".")        f.seek(pos + 22)   # size of 'ZIP end of central directory record'       f.truncate()        f.close()    else:        # raise error, file is truncated   
like image 134
astronautlevel Avatar answered Oct 01 '22 15:10

astronautlevel