content
将是整个文件(字节),你可以写出来。
import requests
r = requests.get('...YOUR URL...')
# Create a file to write to in binary mode and just write out
# the entire contents at once.
# Also check to see if we get a successful response (add whatever codes
# are necessary if this endpoint will return something other than 200 for success)
if r.status_code in (200,):
with open('tarfile.tar', 'wb') as tarfile:
tarfile.write(r.content)
如果您正在下载任意tar文件,它可能是相当大的,你可以choose to stream it来代替。
import requests
tar_url = 'YOUR TAR URL HERE'
rsp = requests.get(tar_url, stream=True)
if rsp.status_code in (200,):
with open('tarfile.tar', 'wb') as tarfile:
# chunk size is how many bytes to read at a time,
# feel free to adjust up or down as you see fit.
for file_chunk in rsp.iter_content(chunk_size=512):
tarfile.write(chunk)
需要注意的是这种模式(打开一个文件,wb
模式)一般应编写任何类型的二进制文件的工作。我建议阅读writing file documentation for Python 3(Python 2 documentation here)。