2015-10-16 193 views
-3

我必须使用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

你打开在'b'inary模式下的文件? –

+2

添加您正在使用的代码 –

回答

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) 
+0

您可能需要'r.raw.decode_content = True',来处理Content-Encoding标头。 – jfs

+0

谢谢,使用r.content解决了这个问题。 – pseudomarvin