Skip to content
Home » BadZipFile: File is not a zip file while unzipping a file

BadZipFile: File is not a zip file while unzipping a file

To solve unzipping file results in “BadZipFile: File is not a zip file” error follow below methods.

ERROR LOG

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

How to solve unzipping file results in “BadZipFile: File is not a zip file” ?

Refer the given methods to solve the issue.

Method 1:

def fixBadZipfile(zipFile):  
 f = open(zipFile, 'r+b')  
 data = f.read()  
 pos = data.find('\x50\x4b\x05\x06')  
 if (pos > 0):  
     self._log("Trancating file at location " + str(pos + 22)+ ".")  
     f.seek(pos + 22)   
     f.truncate()  
     f.close()  
 else:  
     # raise error

Method 2 :

Although astronautlevel’s method works in most circumstances, the compressed data and CRCs in the Zip file can also contain the same 4 bytes. You should do an rfind (not a find), seek to pos+20, and then add write x00x00 to the end of the file (this tells zip applications that the ‘comments’ section is 0 bytes long).

    content = zipFileContainer.read()
    pos = content.rfind('\x50\x4b\x05\x06') 
    if pos>0:
        zipFileContainer.seek(pos+20)
        zipFileContainer.truncate()
        zipFileContainer.write('\x00\x00') 
        zipFileContainer.seek(0)

    return zipFileContainer

Hope the above solution works.

Also read :

BadZipFile: File is not a zip file while unzipping a file