【问题标题】:Write binary data from a string to a binary file将二进制数据从字符串写入二进制文件
【发布时间】:2016-01-15 15:59:19
【问题描述】:

我有一个使用requests.get()获取的torrent文件,存储在一个字符串中,如下所示:

import requests
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept-Charset': 'utf-8',
'Connection': 'keep-alive'}
request = requests.get(url, headers=headers)
data = requests.text

我想将其写入二进制文件,以便其中的数据正确且有效:

with open(name, "wb") as f:
    f.write(data)

但是我似乎无法将字符串写为纯二进制数据,因为 python 一直试图将其解释为 Unicode,我收到如下错误:"UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-9: ordinal not in range (128)。

我曾尝试使用 bytearray 但出现类似问题:TypeError: unicode argument without an encoding。

有没有办法将字符串中的字节原样写入文件?

【问题讨论】:

  • 您是在binary 模式下打开文件吗?
  • 添加你正在使用的代码

标签: python python-2.7 unicode python-requests binaryfiles


【解决方案1】:
  • 使用response.content,而不是response.text。
  • 使用"wb"打开文件进行二进制输出。

示例程序:

import requests

r = requests.get("http://httpbin.org/image/png")
with open("image.png", "wb") as out_file:
    out_file.write(r.content)

一个稍微花哨的程序,对于巨大的文件占用更少的内存:

import requests
import shutil

r = requests.get("http://httpbin.org/image/png", stream=True)
with open("image.png", "wb") as out_file:
    shutil.copyfileobj(r.raw, out_file)

【讨论】:

  • 您可能希望r.raw.decode_content = True 处理Content-Encoding 标头。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 2020-08-28
  • 2015-07-02
  • 1970-01-01
  • 2012-09-22
  • 2016-10-03
  • 2010-10-15
相关资源
最近更新 更多