# Python requests 如何上传文件

URL: https://caijiao.org/how-to/python/upload-file
Source: docs/how-to/python/upload-file.md
Description: Python requests 如何上传文件：用 files 参数传文件对象，with 块确保文件关闭。 包含脚本示例、处理提醒和相关 Python、工具内容入口。

## 快速答案

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

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

## 使用要点

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

## 相关内容

- [Python 问题](/how-to/python/)
- [Python 教程](/python/)
- [Python 文件处理项目](/python/ch11/project-filetool)
- [正则表达式测试工具](/tool/regex-tester)
- [JSON Formatter](/tool/json-formatter)
