将字符串中的二进制数据写入二进制文件

pse*_*vin 0 python unicode binaryfiles python-2.7 python-requests

我有一个通过使用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
Run Code Online (Sandbox Code Playgroud)

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

with open(name, "wb") as f:
    f.write(data)
Run Code Online (Sandbox Code Playgroud)

然而,我似乎无法将字符串写为纯二进制数据,因为 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

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

Rob*_*obᵩ 9

  • 使用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)
Run Code Online (Sandbox Code Playgroud)

一个稍微花哨的程序,对于巨大的文件来说内存占用较小:

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)
Run Code Online (Sandbox Code Playgroud)