Unzip. corrupted zip with python

Asked

Viewed 45 times

1

I have the following situation, I need to unzip ". zip" files, the code I am using is this:

from zipfile import ZipFile
from tkinter import Tk
from tkinter import filedialog as dlg
from tkinter.filedialog import askopenfilename
import os, sys

password = b'senha123'

destino = 'C:/Users/usuario/Desktop/teste1'

Tk().withdraw() #Torna a janeka do tk invisivel

arq = askopenfilename() #seleciona um arquivo
zf = ZipFile(arq ,'r')

zf.extractall(path=destino, pwd=password)

zf.close()
print('Extração feita...')

The files ". zip" contains photos inside it, but sometimes some photos comes corrupted, which makes it end up corrupting the file ". zip" too, but if I use 7-Zip manually I can unzip the zip normally, but with Pyhton it gives this error here:

Traceback (most recent call last):
  File "C:\Users\usuario\Documents\Cah\Pyton\proj_zip\teste_extracao_zips.py", line 17, in <module>
    zf = ZipFile(arq ,'r')
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python38\lib\zipfile.py", line 1267, in __init__
    self._RealGetContents()
  File "C:\Users\usuario\AppData\Local\Programs\Python\Python38\lib\zipfile.py", line 1334, in _RealGetContents
    raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file

So far I couldn’t find a solution to this, I tried to use the library py7zr, shutil and pyunpack but I didn’t get any results, could help me with this?

  • By awakening consciousness, there would be the possibility of providing a link to one of these corrupted zips for testing?

1 answer

1

if you have another program that can open the zip, the best thing to do is to unpack elsewhere and recreate the zip;

The work of investigating that broke with the Python zipfile when opening these files, and makes it "tolerant" - either to default, or the change of compatibility of the new version would be orders of magnitude greater than simply create a zip that works.

If you receive defective zip files frequently, what you can do is instead of using ziplib, call an external decompression program, such as 7zip, using subprocess.run (the rich cousin of os.system). But that’s it. If it’s only one file, or few broken files, better just recreate the files and use the same zipfile.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.