我有一个使用存储在字符串中的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
。
有没有办法只将字符串中的字节写入文件?
答案 0 :(得分:2)
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)