簡體   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