urlretrieve()的使用

以下代码可用于简单下载文件
# 环境python3.8
import urllib.request as ureq
import os
import time


# 定义回调函数
def callback(cur_down, cur_size, total_size):
    """
    回调函数
    :param cur_down: 已经下载的数据块数
    :param cur_size:数据块的字节数
    :param total_size:文件总字节数
    :return:
    """
    temp = 100 * cur_down * cur_size / total_size
    progress = temp if temp < 100 else 100
    print("%5.1f%%" % progress)


# url = "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2967603991,4237017423&fm=26&gp=0.jpg"
url = "https://pcclient.download.youku.com/ikumac/youkumac_1.8.9.12225.dmg?spm=a2hpd.20022519.m_235549.5~5~5~5!2~P!3~A&file=youkumac_1.8.9.12225.dmg"
# 获取当前脚本文件的路径
# filepath = os.path.abspath(__file__)


# 获取当前文件夹的路径
folder = os.path.abspath('.')

# 获取url中的文件名称
file_name = os.path.basename(url)
# print(file_name)

# 文件陆路径
file_path = os.path.join(folder, file_name)

if not os.path.isfile(file_path):
    start_time = time.time()
    print("Downloading File From %s" % url)
    # 返回本地文件名称,mime信息
    file_name1, mime = ureq.urlretrieve(url=url, filename=file_path, reporthook=callback)
    print("\nFinished!")
    end_time = time.time()
    # 获取文件大小
    filesize = os.path.getsize(file_path)
    print("Totally download %f mb" % (filesize / 1024 / 1024))
    print("Totally Used %f s" % (end_time - start_time))
else:
    print("File %s Already Exist!" % file_name)

# print(str(message))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值