python如何下载网络文件到本地指定文件夹

 更新时间:2025年05月18日 11:14:16   作者:MartinYangHJ  
这篇文章主要为大家详细介绍了python如何实现下载网络文件到本地指定文件夹,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

 在Python中下载文件到本地指定文件夹可以通过以下步骤实现,使用requests库处理HTTP请求,并结合os模块处理文件路径:

import requests, os,datetime
from urllib.parse import urlparse,parse_qs
 
"""
获取request header信息,Cookie根据网址需要自己设定
"""
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7;application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Cookie': '132213213213213213',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
 
 
def download_file(url, save_dir=None,file_name=None):
    """
    下载文件并保存到指定路径,,从网络路径中获取文件名,例如https://127.0.0.1:8000/web/file/5ed63734774b40d181fd96e1c58133d2.pdf
    :param url: 文件下载URL
    :param save_dir: 文件保存路径
    :param file_name: 文件名
    """
    try:
        if file_name is None:
            parse_url=urlparse(url)
            file_name=os.path.basename(parse_url.path)
            if not file_name:
                file_name="download_file_"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        if save_dir is None:
            save_dir=rf"C:\Users\Desktop\download_file"
        save_path=os.path.abspath(save_dir)
        file_path=os.path.join(save_path,file_name)
 
        if save_dir and not os.path.exists(save_dir):
            os.makedirs(save_dir, exist_ok=True)
 
        # 发起带流式传输的GET请求
        with requests.get(url, stream=True,headers=headers) as response:
            response.raise_for_status()  # 检查HTTP状态码
 
            # 分块写入文件
            with open(file_path, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:  # 过滤保持连接的空白块
                        file.write(chunk)
 
        print(f"文件下载成功,保存路径:{file_path}")
        return True
    except requests.exceptions.RequestException as e:
        print(f"网络请求失败:{str(e)}")
    except IOError as e:
        print(f"文件操作失败:{str(e)}")
    except Exception as e:
        print(f"未知错误:{str(e)}")
 
    return False
 
 
def download_file2(url, save_dir=None,file_name=None):
    """
        下载文件并保存到指定路径,从网络路径中获取文件名,例如https://127.0.0.1:8000/web/file/5ed63734774b40d181fd96e1c58133d2.pdf
        :param url: 文件下载URL
        :param save_dir: 文件保存路径
        :param file_name: 文件名
    """
    try:
        if file_name is None:
            parse_url = urlparse(url)
            file_name = os.path.basename(parse_url.path)
            if not file_name:
                file_name = "download_file_" + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        if save_dir is None:
            save_dir = rf"C:\Users\Desktop\download_file"
        save_path = os.path.abspath(save_dir)
        file_path = os.path.join(save_path, file_name)
 
        if save_dir and not os.path.exists(save_dir):
            os.makedirs(save_dir, exist_ok=True)
 
        response = requests.get(url, stream=True, headers=headers)
        response.raise_for_status()
        with open(file_path, 'wb') as file:
            file.write(response.content)
        return True
    except requests.exceptions.RequestException as e:
        print(f"网络请求失败:{str(e)}")
    except IOError as e:
        print(f"文件操作失败:{str(e)}")
    except Exception as e:
        print(f"未知错误:{str(e)}")
 
    return False
 
 
def download_file3(url, save_dir=None,file_name=None):
    """
        下载文件并保存到指定路径,从网络路径中query参数中获取文件名,例如https://127.0.0.1:8000/web/file?path=2025041616372016\\5ed63734774b40d181fd96e1c58133d2.pdf
        :param url: 文件下载URL
        :param save_dir: 文件保存路径
        :param file_name: 文件名
    """
    try:
        if file_name is None:
            parse_url = urlparse(url)
            # 从query参数中提取文件名
            query_params = parse_qs(parse_url.query)
            # 获取 path 参数的值,path可根据实际情况进行调整
            path_value = query_params.get('path', [''])[0]
 
            # 提取文件名(最后一个反斜杠后的部分)
            file_name = path_value.split('\\')[-1]
            if not file_name:
                file_name = "download_file_" + datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        if save_dir is None:
            save_dir = rf"C:\Users\Desktop\download_file"
        save_path = os.path.abspath(save_dir)
        file_path = os.path.join(save_path, file_name)
 
        if save_dir and not os.path.exists(save_dir):
            os.makedirs(save_dir, exist_ok=True)
 
        response = requests.get(url, stream=True, headers=headers)
        response.raise_for_status()
        with open(file_path, 'wb') as file:
            file.write(response.content)
        return True
    except requests.exceptions.RequestException as e:
        print(f"网络请求失败:{str(e)}")
    except IOError as e:
        print(f"文件操作失败:{str(e)}")
    except Exception as e:
        print(f"未知错误:{str(e)}")
 
    return False

使用示例

# 示例1:自动从URL提取文件名
download_file(
    url="https://example.com/report.pdf",
    save_dir="./downloads"
)
 
download_file2(
    url="https://example.com/report.pdf",
    save_dir="./downloads"
)
 
# 示例2:自定义文件名
download_file(
    url="https://example.com/data?format=csv",
    save_dir="./data_files",
    file_name="dataset.csv"
)
 
download_file2(
    url="https://example.com/data?format=csv",
    save_dir="./data_files",
    file_name="dataset.csv"
)
 
# 示例3:从网络路径中query参数中获取文件名
download_file3(
    url="https://example.com/data?path=20250417\\example.csv",
    save_dir="./data_files",
    file_name="example.csv"
)

关键点说明

文件名处理:

默认从URL路径中提取文件名(如https://a.com/b.zip提取b.zip)。

若URL不包含文件名(如以/结尾),则使用默认名称downloaded_file。

支持通过参数file_name自定义文件名。

支持从URL路径的Query参数中获取文件名(如https://example.com/data?path=20250417\\example.csv提取example.csv)

路径处理:

使用os.path模块确保路径跨平台兼容。

自动创建目标目录(若不存在)。

流式下载:

使用stream=True分块下载,避免大文件占用过多内存。

通过iter_content逐块写入,提升可靠性。

异常处理:

捕获常见错误(如网络问题、权限不足)。

使用response.raise_for_status()检查HTTP状态码。

扩展性:

支持自定义请求头(如模拟浏览器访问)。

可调整chunk_size优化下载速度与内存占用。

方法补充

python下载文件到指定文件夹

# coding:utf-8
import os
import shutil
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# print os.getcwd()
# 有些文件夹下面有很多文件夹,每个文件夹下面有很多视频文件,现在通过脚本,将文件夹下面的所有文件转移到一个目录下面
# 统计访问的文件夹数量及文件数量
countNum = [0, ]countFile = [0, ]# 选择全部移除或者指定后缀名文件
# 查找文件
def move_all_files(dir_path):
if os.path.exists(dir_path):
countNum[0] += 1
# 输出遍历的文件夹数量
print "*****", countNum[0], "*****"+dir_path
# 指定文件夹下的所有文件和文件夹
path_list = os.listdir(dir_path)
# 遍历
for each_path in path_list:
# 如果是文件夹就继续遍历
print each_path
if os.path.isdir(dir_path+""+each_path):
# 移动所有文件到指定目录下面
src=dir_path+""+each_path
move_all_files(src)
else:
# 如果是指定文件类型,则复制文件
file_type = os.path.splitext(each_path)[1] # 判断是否为选择的文件类型
selected = False
if file_type == select_type or select_type == 'All':
selected = True
if selected:
# 复制文件
src_file = dir_path + "" + each_path
des_file = des_pos + "" + each_path
print "正在复制", each_path
shutil.copyfile(src_file, des_file)
# 文件+1
countFile[0] += 1
else:
print "指定路径不存在"
# 需要复制文件的文件夹位置
give_pos = r"C:UserslanceDownloadsJava Web编程相关"
# 需要复制到的位置
des_pos = r"C:UserslanceDownloads测试"
# All 或者 指定文件后缀名
select_type = 'All'
# 如果不存在,创建
if not os.path.exists(unicode(des_pos, 'utf-8')):
os.mkdir(unicode(des_pos, "utf-8"))
# 移动文件
move_all_files(unicode(give_pos, "utf-8"))
print "将文件从****'", give_pos, "'复制到****'", des_pos, "'"
print "共访问了", countNum[0], "个文件夹"
print "共复制了 ", countFile[0], " 个文件"

到此这篇关于python如何下载网络文件到本地指定文件夹的文章就介绍到这了,更多相关python下载网络文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python超详细讲解元类的使用

    Python超详细讲解元类的使用

    在Python里一切都是对象(object),基本数据类型,如数字,字符串,函数都是对象。对象可以由类(class)进行创建。那么既然一切都是对象,那么类是对象吗?是的,类也是对象,那么又是谁创造了类呢?答案也很简单,也是类,一个能创作类的类,称之为(type)元类
    2022-06-06
  • Python关于维卷积的理解

    Python关于维卷积的理解

    这篇文章主要介绍了Python关于维卷积的理解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • Python之@cache装饰器的使用及说明

    Python之@cache装饰器的使用及说明

    @cache是Python3.9引入的新装饰器,用于缓存函数结果,避免重复计算,提高性能,它基于functools.lru_cache实现,支持无限大小缓存,适用于纯函数,使用示例包括递归斐波那契数列和模拟耗时计算,注意适用场景、参数限制和内存占用,与@lru_cache相比,@cache更简洁,但功能单一
    2025-12-12
  • 深入浅析Python 函数注解与匿名函数

    深入浅析Python 函数注解与匿名函数

    这篇文章主要介绍了Python 函数注解与匿名函数的相关知识,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02
  • Python turtle打造一个浪漫流星雨表白程序

    Python turtle打造一个浪漫流星雨表白程序

    本教程详细介绍使用Python标准库turtle和tkinter实现浪漫表白程序,用户点击好哦后88颗随机流星划划过夜空;点击不要弹出提示框;代码简洁易无需第三方包,适合作为Python教学示例,需要的朋友可以参考下
    2026-06-06
  • 基于Python安装pyecharts所遇的问题及解决方法

    基于Python安装pyecharts所遇的问题及解决方法

    今天小编就为大家分享一篇基于Python安装pyecharts所遇的问题及解决方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-08-08
  • PyTorch 中mm和bmm函数的使用示例详解

    PyTorch 中mm和bmm函数的使用示例详解

    PyTorch中torch.mm用于二维矩阵乘法,torch.bmm处理批量矩阵乘法(三维张量),均不支持广播,两者适用于神经网络权重计算、点云变换等场景,区别在于维度要求和批量处理效率,本文给大家介绍PyTorch 中mm和bmm函数的使用,感兴趣的朋友一起看看吧
    2025-06-06
  • python微信聊天机器人改进版(定时或触发抓取天气预报、励志语录等,向好友推送)

    python微信聊天机器人改进版(定时或触发抓取天气预报、励志语录等,向好友推送)

    这篇文章主要介绍了python微信聊天机器人改进版,定时或触发抓取天气预报、励志语录等,向好友推送 ,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-04-04
  • numpy中的ndarray方法和属性详解

    numpy中的ndarray方法和属性详解

    这篇文章主要介绍了numpy中的ndarray方法和属性详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • django中间键重定向实例方法

    django中间键重定向实例方法

    在本篇文章里小编给各位分享的是关于django中间键重定向实例方法以及相关代码,需要的朋友们学习下吧。
    2019-11-11

最新评论