问题库 Python how-to

Python requests 如何上传文件

快速答案

用 files 参数传文件对象,with 块确保文件关闭。

py
with open('demo.png', 'rb') as f:
    res = requests.post(url, files={'file': f}, timeout=30)

使用要点

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

相关内容