使用以下流代码,无论下载文件的大小如何,都限制了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 chunk: # filter out keep-alive new chunks f.write(chunk) # f.flush() return local_filename请注意,使用返回的字节数
iter_content不完全是
chunk_size;; 它应该是一个通常更大的随机数,并且在每次迭代中都应该有所不同。



