繁体   English   中英

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

[英]Write binary data from a string to a binary file

我有一个通过使用requests.get()获得的种子文件存储在一个字符串中,并像这样获得:

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

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

  • 使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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