python下载文件

def downloadFile(url, filepath):
    """
    下载文件并保存
    :param url:
    :param filepath:
    :return:
    """
    # 获取文件后缀
    # file_extension = os.path.splitext(url)[1]

    # 判断文件是否存在
    if os.path.isfile(filepath):
        # 如果文件存在就利用时间戳改名
        filepath = str(int(time.time())) + "_" + filepath
    try:
        res = requests.get(url)
        file = open(filepath, "wb")
        for chunk in res.iter_content(chunk_size=1024 * 1024):
            file.write(chunk)
        file.close()
    except Exception as e:
        print(e)

 

posted @ 2021-03-23 17:14  SirPi  阅读(50)  评论(0编辑  收藏  举报