python 下载大文件,断点续传 | Python工具类
目录
前言
依赖
工具代码
总结
前言
实用python进行大文件下载的时候,一旦出现网络波动问题,导致文件下载到一半。如果将下载不完全的文件删掉,那么又需要从头开始,如果连续网络波动,是不是要头秃了。本文提供断点续传下载工具方法,希望可以帮助到你。
依赖
os、sys、requests
工具代码
废话不多说,上代码。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 23 13:54:39 2021@author: huyi
"""import os
import sysimport requestsdef download(url, file_path):# 重试计数count = 0# 第一次请求是为了得到文件总大小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(total_size)# 开始下载while count < 10:if count != 0:temp_size = os.path.getsize(file_path)# 文件大小一致,跳出循环if temp_size >= total_size:breakcount += 1print("第[{}]次下载文件,已经下载数据大小:[{}],应下载数据大小:[{}]".format(count, temp_size, total_size))# 重新请求网址,加入新的请求头的# 核心部分,这个是请求下载时,从本地文件已经下载过的后面下载headers = {"Range": f"bytes={temp_size}-{total_size}"}# r = requests.get(url, stream=True, verify=False)r = requests.get(url, stream=True, verify=False, headers=headers)# "ab"表示追加形式写入文件with open(file_path, "ab") as f:if count != 1:f.seek(temp_size)for chunk in r.iter_content(chunk_size=1024 * 64):if chunk:temp_size += len(chunk)f.write(chunk)f.flush()###这是下载实现进度显示####done = int(50 * temp_size / total_size)sys.stdout.write("\r[%s%s] %d%%" % ('█' * done, ' ' * (50 - done), 100 * temp_size / total_size))sys.stdout.flush()print("\n")return file_path
代码说明:
1、重试次数可以自己修改,按照需求来,我这边是10次。
2、增加了进度条的打印,别问,好看就完了。
验证一下,我们准备个文件下载服务。上文件服务代码。代码对flask、gevent有依赖。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 23 19:53:18 2021@author: huyi
"""from flask import Flask, request, make_response, send_from_directory
from gevent.pywsgi import WSGIServer
from gevent import monkey# 将python标准的io方法,都替换成gevent中的同名方法,遇到io阻塞gevent自动进行协程切换
monkey.patch_all()
app = Flask(__name__)@app.route("/download", methods=['GET'])
def download_file():get_data = request.args.to_dict()file_path = get_data.get('fileName')response = make_response(send_from_directory('/Users/huyi/Movies/Videos',file_path,as_attachment=True))response.headers["Content-Disposition"] = "attachment; filename={}".format(file_path.encode().decode('latin-1'))return responseif __name__ == '__main__':WSGIServer(('0.0.0.0', 8080), app).serve_forever()
启动文件下载服务,测试下载代码
download('http://localhost:8080/download?fileName=test.mp4', '/Users/huyi/Downloads/test.mp4')
首先我们下载一部分,然后关闭,模拟下载一半的情况。
重新执行一下,把剩下的执行
OK,验证通过。
总结
断点续传的这部分代码,你可以好好理解一下原理,其实不复杂。还是不明白可以私信我。
如果本文对你有帮助,请点个赞支持一下吧。
python 下载大文件,断点续传 | Python工具类相关推荐
- python下载大文件-golang/python 下载大文件时怎样避免oom
问题场景:高频系统中,agent 会向ATS 服务器发出刷新和预缓存的请求,这里的请求head 里面有GET ,PURGE等,因为一般的预缓存都是小文件,但是某天,突然服务器oom...罪魁祸首发现是 ...
- python下载大文件-使用python通过FTP下载大文件
对不起,如果我回答我自己的问题,但我找到了解决方案. 我尝试了ftputil没有成功,所以我尝试了很多方式,最后,这工作: def ftp_connect(path): link = FTP(host ...
- python 下载大文件
python 下载大文件 文件过大,建议用迅雷 下载大文件 import os import time import requests# 下载大文件 def download_data(url, pa ...
- python下载大文件-使用请求在python中下载大文件
请求是一个非常好的库.我想用它下载大文件(>1GB).问题是不可能将整个文件保存在内存中,我需要将其分块读取.以下代码有问题 1 2 3 4 5 6 7 8 9 10 11import requ ...
- python下载大文件-python requests 下载大文件不完整
目前我有一个脚本, 从帝联的 CDN 外链获取一下文件作为备份. 使用的是 Python 2.7.10 requests 2.8.1 目前碰到一个情况, 使用 requests 下载大文件的时候会出现 ...
- python下载大文件
1. wget def download_big_file_with_wget(url, target_file_name):"""使用wget下载大文件Note: 需要 ...
- python读取大文件-使用Python读取大文件的方法
背景 最近处理文本文档时(文件约2GB大小),出现memoryError错误和文件读取太慢的问题,后来找到了两种比较快Large File Reading 的方法,本文将介绍这两种读取方法. 准备工作 ...
- python下载大文件-python 大文件
广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 大文件上传服务一.前端(http:fex.baidu.comwebuploade ...
- python下载代码-python下载大文件代码
如果下载小文件,可以直接使用urllib.urlretrieve方法: import urllib urllib.urlretrieve ("http://www.example.com/s ...
最新文章
- 基于深度学习的医学图像半监督分割
- jQuery日期和时间插件(jquery-ui-timepicker-addon.js)中文破解版使用
- asp.net select Case条件语句的使用方法
- c语言不会可以学好java吗_C语言一定要学好吗?
- python vs java 搞笑视频_Python VS Java,谁能笑到最后?
- c语言 error 9,C语言求助(_) c:9: error: syntax error before '[' token
- 【转】人工智能教程-前言
- 30秒解决电脑越用越卡的大众常见难题
- js中应用protocol buffer
- grafana 迁移
- openssl 签发证书相关命令
- 排列组合问题的通用算法
- 深度学习第四次培训(SVM算法)
- 使用计算机语言编程是用几进制,使用计算机高级语言编程,将下列变量值的二进制编码打印输出。请给出程序源代码和输出结果(可截屏):...
- (二)TCP客户端/服务器通信------select函数
- mxnet 运行自己的数据
- 用python的statamodels模块拟合VAR模型
- sql server 获取当前日期前三十天的日期
- 服务器配置80端口文件在哪,给服务器配置一个80端口
- Adobe Dreamweave下载和安装步骤