Python3 requests文件下载 期间显示文件信息和下载进度代码实例

yipeiwu_com6年前Python基础

这篇文章主要介绍了Python3 requests文件下载 期间显示文件信息和下载进度代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

"""使用模块线程方式实现网络资源的下载
# 实现文件下载, 期间显示文件信息&下载进度
# 控制台运行以显示进度
"""
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")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Windows上使用virtualenv搭建Python+Flask开发环境

关于virtualenv: VirtualEnv用于在一台机器上创建多个独立的Python虚拟运行环境,多个Python环境相互独立,互不影响,它能够: 1.在没有权限的情况下安装新套件...

python3中的eval和exec的区别与联系

看了很多网上的方法,写入文件后打开文件看确实不再是乱码,但是从文件中读入json时发现了乱码,可能是读文件默认的编码格式不对。下面读写方法可行。 注意,ensure_ascii=Fals...

Python使用matplotlib绘制三维参数曲线操作示例

Python使用matplotlib绘制三维参数曲线操作示例

本文实例讲述了Python使用matplotlib绘制三维参数曲线操作。分享给大家供大家参考,具体如下: 一 代码 import matplotlib as mpl from mpl...

Python实现定时备份mysql数据库并把备份数据库邮件发送

一、先来看备份mysql数据库的命令 mysqldump -u root --password=root --database abcDataBase > c:/abc_bac...

Python 类,property属性(简化属性的操作),@property,property()用法示例

本文实例讲述了Python 类,property属性(简化属性的操作),@property,property()用法。分享给大家供大家参考,具体如下: property属性的创建方式有两...