尝试写入文件并将其同时附加到 Zip 文件夹时出现类型错误

Getting TypeError When Trying To Write To A File And Append It To a Zip folder at same time

我想将一些信息写入文本文件,在循环完成后将信息写入该文本文件,将该文件放入 zip 文件夹。这是我现在拥有的。

import zipfile

    file_names = ['oranges.txt', 'lemonade.txt', 'mango.txt']

    for file in file_names:

        text_file_name = f"{file}.txt"
        counter = 1

        zf = zipfile.ZipFile('food_data.zip', "w", zipfile.ZIP_DEFLATED)
        response = requests.get(f"api.farmers.com?page={counter}")

        if response.json != []:
            with ZipFile("food_data.zip", "w") as zip:
                with zip.open(file, "w") as f:
                    f.write("Confirmed API is working!")
                    counter += 1
                    
           zf.writestr(file_name, json.dumps(response.json()))
    >>>>  **TypeError: a bytes-like object is required, not 'str'**
            

I've tried to add "rb" to the write mode in `ZipFile("food_data.zip", "w") as zip:` but then I get the error message `ValueError: ZipFile requires mode 'r', 'w', 'x', or 'a'` 

这是我正在阅读的 ZipFile 文档:https://docs.python.org/3/library/zipfile.html

试试这个方法:

file = 'file.txt'

zipfile.ZipFile('food_data.zip', "w", zipfile.ZIP_DEFLATED)
zf.writestr(file, "Hello! Confirmed that API is working!")
zf.close()