python怎么实现文件下载功能

   2025-02-13 3360
核心提示:在Python中,可以使用requests库来实现文件下载功能。以下是一个简单的示例:import requestsdef download_file(url, save_

在Python中,可以使用requests库来实现文件下载功能。以下是一个简单的示例:

import requestsdef download_file(url, save_path):    response = requests.get(url)    with open(save_path, 'wb') as file:        file.write(response.content)# 调用示例url = 'http://example.com/file.txt'  # 文件的URLsave_path = 'path/to/save/file.txt'  # 保存的文件路径download_file(url, save_path)

在这个例子中,我们定义了一个download_file函数,它接收文件的URL和保存的路径作为参数。函数使用requests.get方法发送GET请求获取文件内容,然后使用open函数以二进制写入模式打开保存路径,并调用write方法将文件内容写入文件。

请注意,这个示例只适用于小文件的下载。如果要下载大文件,可能需要使用流式方式来处理,以避免一次将整个文件内容加载到内存中。可以使用iter_content方法来逐块下载文件内容。下面是一个示例:

import requestsdef download_large_file(url, save_path, chunk_size=128):    response = requests.get(url, stream=True)    with open(save_path, 'wb') as file:        for chunk in response.iter_content(chunk_size=chunk_size):            file.write(chunk)# 调用示例url = 'http://example.com/large_file.zip'  # 大文件的URLsave_path = 'path/to/save/large_file.zip'  # 保存的文件路径download_large_file(url, save_path)

在这个示例中,我们设置stream=True来启用流式下载。然后,我们使用iter_content方法来迭代下载的块,并将每个块写入文件。这样可以在下载大文件时避免将整个文件内容加载到内存中。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言