# Python 如何复制文件和目录

URL: https://caijiao.org/how-to/python/copy-files
Source: docs/how-to/python/copy-files.md
Description: Python 如何复制文件和目录：文件用 shutil.copy2，目录用 shutil.copytree。 包含脚本示例、处理提醒和相关 Python、工具内容入口。

## 快速答案

文件用 shutil.copy2，目录用 shutil.copytree。

```py
import shutil
shutil.copy2('a.txt', 'backup/a.txt')
shutil.copytree('docs', 'docs-backup', dirs_exist_ok=True)
```

## 使用要点

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

## 相关内容

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