简体   繁体   中英

Save API unicode response to zip file python

When I hit post API, it is returning a zip file content as an output (which is in unicode form) and I want to save those content in zipfile locally.

How can I save the same?

Trials :

Try 1:

`//variable data containing API response. (i.e data = response.text)
f = open('test.zip', 'wb')
f.write(data.encode('utf8'))
f.close()`

Above code creating zip file. But the file is corrupted one.

Try 2

with zipfile.ZipFile('spam.zip', 'w') as myzip: myzip.write(data.decode("utf8"))

Above code giving me an error: UnicodeEncodeError: 'ascii' codec can't encode character u'\�' in position 97: ordinal not in range(128)

Can anyone help me to resolve the same?

when reading and writing binary data, make sure to open your files in binary mode:

f = open('test.zip', 'w')

should be

f = open('test.zip', 'wb')

what do you mean by "corrupted" you cant open it with a zip manager? becuase the file created here isnt really a zip file



reading the zipfile documentation i see that write takes a file name, it doesnt compress arbitrary data, you can use zlib for that
you can also use the writestr function of zipfile, but then you need to provide a file name under which your string will be

I found the answer for above problem. May be someone in future wants the same. So writing answer for my own question.

response.content instead of response.text resolved my problem.

import requests
response = requests.request("POST", <<url>>, <<payload>>, <<headers>>, verify=False)
data = response.content

f = open('test.zip', 'w')
f.write(data)
f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM