python requests下载文件_requests实现文件下载, 期间显示文件信息&下载进度_python3...

"""使用模块线程方式实现网络资源的下载

# 实现文件下载, 期间显示文件信息&下载进度

# 控制台运行以显示进度

"""

import requests

import os.path as op

import os

from sys import stdout

def downloadfile(url, filename):

"""下载文件并显示过程

:param url: 资源地址

:param filename: 保存的名字, 保存在当前目录

"""

# print(url)

filename = filename + '.' + op.splitext(url)[-1]

file_to_save = op.join(os.getcwd(), filename)

# print(file_to_save)

with open(file_to_save, "wb") as fw:

with requests.get(url, stream=True) as r:

# 此时只有响应头被下载

# print(r.headers)

print("下载文件基本信息:")

print('-' * 30)

print("文件名称:", filename)

print("文件类型:", r.headers["Content-Type"])

filesize = r.headers["Content-Length"]

print("文件大小:", filesize, "bytes")

print("下载地址:", url)

print("保存路径:", file_to_save)

print('-' * 30)

print("开始下载")

chunk_size = 128

times = int(filesize) // chunk_size

show = 1 / times

show2 = 1 / times

start = 1

for chunk in r.iter_content(chunk_size):

fw.write(chunk)

if start <= times:

stdout.write(f"下载进度: {show:.2%}\r")

start += 1

show += show2

else:

stdout.write("下载进度: 100%")

print("\n结束下载")

if __name__ == "__main__":

downloadfile("https://code.jquery.com/jquery-3.4.1.js", "a")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值