Excel 在 Python 中使用 zipfile 写入方法后文件损坏

Excel file corrupted after using zipfile write method in Python

我正在开发一个 Flask 应用程序,我希望用户从服务器下载一组文件。为了实现这个 objective,我使用 zipfile 模块来压缩所有文件,然后将这个压缩文件发送给用户。

这是我的代码:

@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
    )

不幸的是,一旦我解压缩 zip 文件,Excel 文件就会损坏(CSV 和 JSON 文件可以毫无问题地读取和打开)。我在编写zip文件时尝试了几种不同类型的编码,但是我一直无法找到解决方案。

有什么问题,我该如何正确执行此操作?

您以文本模式打开文件,这适用于 JSON 和 CSV,但不适用于像 Excel.

这样的二进制文件
open(file_path + ext, "r")

您需要以二进制模式打开它们,即rb = 读取二进制。