'Excel file corrupted after using zipfile write method in Python

I'm developing a Flask application where I want the user to download a set of files from the server. To achieve this objective, I use the zipfile module in order to zip all the files and then send this compressed file to the user.

Here is my code:

@app.route("/get_my_files/<file_name>", methods = ["GET"])
def get_my_files(file_name):

    file_exts = [".csv", ".xlsx", ".json"]
    file_path = "./user_files/" + file_name

    # Create compress file.
    memory_file = io.BytesIO()
    with zipfile.ZipFile(memory_file, 'w') as zf:
        for ext in file_exts:
            #data = zipfile.ZipInfo(individualFile)
            data = zipfile.ZipInfo("resultado" + ext)
            data.date_time = time.localtime(time.time())[:6]
            data.compress_type = zipfile.ZIP_DEFLATED
            zf.writestr(data, open(file_path + ext, "r").read())
      
    memory_file.seek(0)

    # , encoding="ISO-8859-1"
    
    # Delete files.
    for ext in file_exts: 
        os.remove(file_path + ext)

     # Return zip file to client.
    return send_file(
        memory_file, 
        mimetype = "zip",
        attachment_filename='resultados.zip', 
        as_attachment=True, 
        cache_timeout=0
    )

Unfortunately, once I decompress the zip file, the Excel file is getting corrupted (CSV and JSON file can be read and opened without problems). I have tried several different types of encoding when writing the zip file, however I haven't been able to find a solution.

What is the problem and how can I do this correctly?



Solution 1:[1]

You opened the files in text mode, which worked for JSON and CSV, but not for a binary file like Excel.

open(file_path + ext, "r")

You need to open them in binary mode, that is rb = read binary.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1