'Getting TypeError When Trying To Write To A File And Append It To a Zip folder at same time
I want to write some information to a text file and after my loop is done writing information to this text file, throw that file to a zip folder. Here's what I have right now.
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'`
This is the documentation for ZipFile that I was reading about: https://docs.python.org/3/library/zipfile.html
Solution 1:[1]
Try this method:
file = 'file.txt'
zipfile.ZipFile('food_data.zip', "w", zipfile.ZIP_DEFLATED)
zf.writestr(file, "Hello! Confirmed that API is working!")
zf.close()
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 |
