Python下载进度条+断点传输

这篇博客简单介绍python断点续传下载文件,并加入花哨的下载进度显示方法,涉及Python文件操作的技巧,和一些函数库的使用。

环境
Python 3.6 
requests模块 
对应文件的下载链接 (要下载的文件必须支持断点续传) 
(是不是很少东西?那必须,python就是这么强大!)

干货
下面直接上代码,关键是简单易懂,复制就能用,拿走不谢。

import sys
import requests
import os
 
# 屏蔽warning信息
requests.packages.urllib3.disable_warnings()
 
def download(url, file_path):
    # 第一次请求是为了得到文件总大小
    r1 = requests.get(url, stream=True, verify=False)
    total_size = int(r1.headers['Content-Length'])
 
    # 这重要了,先看看本地文件下载了多少
    if os.path.exists(file_path):
        temp_size = os.path.getsize(file_path)  # 本地已经下载的文件大小
    else:
        temp_size = 0
    # 显示一下下载了多少   
    #print(temp_size)
    #print(str(total_size/1000000)+'M')
    # 核心部分,这个是请求下载时,从本地文件已经下载过的后面下载
    headers = {'Range': 'bytes=%d-' % temp_size}  
    # 重新请求网址,加入新的请求头的
    r = requests.get(url, stream=True, verify=False, headers=headers)
 
    # 下面写入文件也要注意,看到"ab"了吗?
    # "ab"表示追加形式写入文件
    with open(file_path, "ab") as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk: 
                temp_size += len(chunk)
                f.write(chunk)
                f.flush()
 
                ###这是下载实现进度显示 25表示格子的数目####  
                done = int(25 * temp_size / total_size)
                sys.stdout.write("\r[%s%s] %d%%" % ('█' * done, ' ' * (25 - done), 100 * temp_size / total_size)+'          ('+str(round(temp_size/1000000,1))+'M/'+str(round(total_size/1000000,1))+'M'+')')
                sys.stdout.flush()
    print()  # 避免上面\r 回车符
 
 
if __name__ == '__main__':
    #link = r'https://api.gdc.cancer.gov/data/'
    #UUID = r'2a4a3044-0b1a-4722-83ed-43ba5d6d25b0'
    path = r'F:\1\1.PDF'
    url = "http://www.waveshare.net/datasheet/ST_PDF/STM8S208xx.PDF"
    # 调用一下函数试试
    download(url, path)    

效果图:



作者:Mr番茄蛋 
来源:CSDN 
原文:https://blog.csdn.net/qq_35203425/article/details/80987880 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/qq_36328915/article/details/86661236