Python 使用requests从 URL 下载文件

语言:
Python
6 浏览
0 收藏
2小时前

代码实现

Python
import requests

def download_file(url, filename):
    response = requests.get(url, stream=True)
    with open(filename, "wb") as f:
        for chunk in response.iter_content(1024):
            f.write(chunk)

# Usage
download_file("https://example.com/file.zip", "output.zip")

使用 requests 库从 URL 下载文件并保存到本地。

#requests#下载

片段说明

  • 使用 stream=True 防止一次性加载大文件
  • 建议加异常处理,检查 status_code == 200
  • 可用于下载数据集、图片、配置文件

评论

加载中...