我想下载带有Python请求库的文件。问题是,当我失去与网络的连接时,必须再次下载文件。问题是:如何使程序知道他最后完成的位置并从此开始下载文件?
我将下面的代码粘贴
res = requests.get(link)
playfile = open(file_name, 'wb')
for chunk in res.iter_content(100000):
playfile.write(chunk)
答案 0 :(得分:0)
可以通过Range
从检查点继续下载。实际上,您的问题类似于How to `pause`, and `resume` download work?。
这是显示其工作方式的示例。
import requests
def DownloadFile(url):
local_filename = url.split('/')[-1]
with requests.Session() as s:
r = s.get(url,headers={"Range": "bytes=0-999"})
with open(local_filename, 'wb') as fd:
fd.write(r.content)
r2 = s.get(url,headers={"Range": "bytes=1000-"})
with open(local_filename, 'ab') as fd:
fd.write(r2.content)
return
url = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/BBC_Radio_logo.svg/210px-BBC_Radio_logo.svg.png"
DownloadFile(url)
现在,我们可以建立一个功能,开始从检查点开始对文件进行下载。
import requests
import os
def Continue_(url):
local_filename = url.split('/')[-1]
with requests.Session() as s:
if os.path.exists(local_filename):
position = os.stat(local_filename).st_size
else:
position = 0
r2 = s.get(url,headers={"Range": "bytes={}-".format(position)})
with open(local_filename, 'ab+') as fd:
for c in r2.iter_content():
fd.write(c)
url = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/BBC_Radio_logo.svg/210px-BBC_Radio_logo.svg.png"
def DownloadFile(url):
local_filename = url.split('/')[-1]
with requests.Session() as s:
r = s.get(url,headers={"Range": "bytes=0-999"})
with open(local_filename, 'wb') as fd:
fd.write(r.content)
DownloadFile(url)
Continue_(url)