擅长:python、mysql、java
<p>使用<a href="http://docs.python-requests.org/en/master/api/#requests.Response.raw" rel="noreferrer">^{<cd1>}</a>和<a href="https://docs.python.org/3/library/shutil.html#shutil.copyfileobj" rel="noreferrer">^{<cd2>}</a>会容易得多:</p>
<pre><code>import requests
import shutil
def download_file(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
</code></pre>
<p>这将文件流式传输到磁盘而不使用过多的内存,并且代码很简单。</p>