Harsha Biyani
Harsha Biyani

Reputation: 7268

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'\ufffd' in position 97: ordinal not in range(128)

Can anyone help me to resolve the same?

Upvotes: 0

Views: 1582

Answers (1)

Harsha Biyani
Harsha Biyani

Reputation: 7268

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

Upvotes: 1

Related Questions