【问题标题】:Save API unicode response to zip file python将 API unicode 响应保存到 zip 文件 python
【发布时间】:2019-03-11 21:25:05
【问题描述】:

当我点击 post API 时,它会返回一个 zip 文件内容作为输出(采用 unicode 格式),我想将这些内容保存在本地的 zipfile 中。

如何保存?

试验

尝试 1:

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

以上代码创建 zip 文件。但文件已损坏。

试试 2

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

上面的代码给我一个错误:UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 97: ordinal not in range(128)

谁能帮我解决这个问题?

【问题讨论】:

  • f = open('test.zip', 'w') 读取/写入二进制数据时应以'wb' 模式打开文件
  • @Nullman :我也尝试使用wb,这会创建损坏的 zip 文件。它在解压缩文件时给出An error occured while loading archive

标签: python api zip


【解决方案1】:

我找到了上述问题的答案。将来可能会有人想要同样的东西。所以为我自己的问题写答案。

response.content 而不是response.text 解决了我的问题。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 2018-03-30
    • 1970-01-01
    • 2014-03-29
    • 2020-06-21
    • 2012-01-22
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多