问题库 Python how-to

Python 如何下载文件

快速答案

用 stream=True 分块写入,避免大文件一次进内存。

py
with requests.get(url, stream=True, timeout=30) as res:
    res.raise_for_status()
    with open('file.zip', 'wb') as f:
        for chunk in res.iter_content(8192):
            f.write(chunk)

使用要点

  • 把输入目录和输出目录放到变量里,批量处理前先打印将要操作的文件列表。
  • 跨平台脚本优先使用 pathlib,避免手写路径分隔符。

相关内容