温馨提示×

python下载文件功能怎么实现

小亿
99
2023-11-28 03:15:10
栏目: 编程语言

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

import requests

def download_file(url, save_path):
    response = requests.get(url)
    with open(save_path, "wb") as f:
        f.write(response.content)

# 使用示例
url = "http://example.com/file.txt"
save_path = "path_to_save/file.txt"
download_file(url, save_path)

在上述代码中,download_file函数接受一个文件的URL和保存路径作为参数。它使用requests.get方法发送HTTP GET请求并获得响应。然后,使用open函数以二进制写入模式打开文件,将响应内容写入文件中。

需要替换urlsave_path变量为实际的文件URL和保存路径。

0