Requests是一个非常好的图书馆。我想用它来下载大文件(> 1GB)。 问题是不可能将整个文件保存在内存中。我需要分 block 阅读。这是以下代码的问题:
import requests
def DownloadFile(url)
local_filename = url.split('/')[-1]
r = requests.get(url)
f = open(local_filename, 'wb')
for chunk in r.iter_content(chunk_size=512 * 1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.close()
return
由于某种原因,它不能以这种方式工作;在将响应保存到文件之前,它仍会将响应加载到内存中。
最佳答案
使用以下流式代码,无论下载文件的大小如何,Python 内存使用都会受到限制:
def download_file(url):
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter below
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
# If you have chunk encoded response uncomment if
# and set chunk_size parameter to None.
#if chunk:
f.write(chunk)
return local_filename
请注意,使用 iter_content
返回的字节数并不完全是 chunk_size
;它应该是一个通常更大的随机数,并且在每次迭代中都会有所不同。
见 body-content-workflow和 Response.iter_content供进一步引用。
关于python - 使用请求在python中下载大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16694907/