How to decode an encoded zipfile using Python?

7.9k Views Asked by At

I have a base64 encoded zip file. I am able to convert that zip file and then extract its content using Windows commandline. I have been trying to do the same with Python, but unsuccessful. Could you please help me? When I run the following code:

import base64
import codecs
import zlib
import io, zipfile, json, pprint

d = open("data.txt", "rb").read()
#dd = base64.decodestring(d)
#print(dd)
z = zipfile.ZipFile(io.BytesIO(d))
unpack = zlib.decompress(d)

I get the following error:

raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file

The data.txt file contains the base64 string: enter image description here

2

There are 2 best solutions below

1
Antony On

A friend of mine helped me. I thought posting the solution here might help a lot of beginners like me:

def convert(d,name, ex):
    with open('output_file.zip', 'wb') as result:
        result.write(base64.b64decode(d))
    zip_ref = zipfile.ZipFile("output_file.zip", 'r')
    zip_ref.extractall("extracted_file")
    zip_ref.close()
        
    for filename in os.listdir("extracted_file"):
        extracted_file = "extracted_file/"+filename
        shutil.move(extracted_file, "images/"+name+ex)
1
Uriel Ezequiel Palma Chavez On
 with zipfile.ZipFile("archivo.zip", "r") as zip_ref:
        # Iterar a través de cada archivo en el archivo ZIP
        for file in zip_ref.namelist():
            # Leer el contenido del archivo y codificarlo en base64
            with zip_ref.open(file) as file_content:
                encoded_content = base64.b64encode(file_content.read())
                # Agregar los datos a la lista
                data_to_insert.append((file, encoded_content))