2015-10-16 189 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