前言
大家好,我是 倔强青铜三 。欢迎关注我,微信公众号: 倔强青铜三。点赞、收藏、关注,一键三连!
今天咱们把 Python 自带的"文件搬运工"------ shutil 模块,从开箱到实战一次性讲透。
一、为什么需要 shutil?
- 复制 / 移动 / 删除 / 打包:比裸 os 模块更高层、更顺手。
- 跨平台:Windows、macOS、Linux 行为一致。
- 零依赖:官方出品,随 Python 一起安装。
shutil 常用 API 一览表
API | 作用 | 关键入参 | 返回值 / 副作用 |
---|---|---|---|
shutil.copy(src, dst) |
复制文件内容 + 权限 | src, dst 可为文件或目录 | 返回新文件路径 |
shutil.copy2(src, dst) |
复制文件内容 + 权限 + 元数据 | 同上 | 同上 |
shutil.copytree(src, dst, dirs_exist_ok=False) |
递归复制整个目录 | src, dst 为目录 | 返回 dst |
shutil.move(src, dst) |
移动文件或目录 | src, dst | 返回 dst |
shutil.rmtree(path) |
递归删除目录 | path | 无 |
shutil.which(cmd) |
在 PATH 中查找可执行文件 | cmd 字符串 | 返回绝对路径或 None |
shutil.make_archive(base, format, root_dir, ...) |
打包为 zip / tar 等 | base 为不含扩展名 | 返回最终归档文件路径 |
shutil.unpack_archive(filename, extract_dir, ...) |
解包归档 | filename, extract_dir | 无 |
shutil.disk_usage(path) |
查看磁盘使用情况 | path | 返回 namedtuple |
shutil.chown(path, user=None, group=None) |
修改文件属主 | path, user, group | 无 |
二、30 秒完成首次文件复制
python
# demo_copy.py
import shutil
import os
os.makedirs("demo_dir", exist_ok=True)
with open("demo_dir/hello.txt", "w", encoding="utf-8") as f:
f.write("hello shutil")
dst = shutil.copy("demo_dir/hello.txt", "demo_dir/hello_copy.txt")
print("复制成功:", dst)
运行效果:
bash
复制成功: demo_dir/hello_copy.txt
三、整目录克隆:copytree
python
# demo_copytree.py
import shutil
import os
src_dir = "src_tree"
dst_dir = "dst_tree"
# 制造源目录
os.makedirs(os.path.join(src_dir, "sub"), exist_ok=True)
with open(os.path.join(src_dir, "sub", "a.txt"), "w") as f:
f.write("a")
shutil.copytree(src_dir, dst_dir)
print("目录树复制完成,dst_tree 存在文件:", os.listdir("dst_tree/sub"))
运行效果:
css
目录树复制完成,dst_tree 存在文件: ['a.txt']
四、移动大法:shutil.move
python
# demo_move.py
import shutil
import os
os.makedirs("from_dir", exist_ok=True)
with open("from_dir/move_me.txt", "w") as f:
f.write("move me")
shutil.move("from_dir/move_me.txt", "move_me.txt")
print("移动后当前目录文件:", [x for x in os.listdir(".") if x.startswith("move_me")])
运行效果:
css
移动后当前目录文件: ['move_me.txt']
五、彻底删除:rmtree
python
# demo_rmtree.py
import shutil
import os
os.makedirs("trash_dir/inside", exist_ok=True)
shutil.rmtree("trash_dir")
print("trash_dir 存在?", os.path.exists("trash_dir"))
运行效果:
python
trash_dir 存在? False
六、查找系统命令:which
python
# demo_which.py
import shutil
python_path = shutil.which("python3") or shutil.which("python")
print("python 可执行文件路径:", python_path)
运行效果(示例,按机器实际路径):
bash
python 可执行文件路径: /usr/bin/python3
七、磁盘用量查询:disk_usage
python
# demo_disk_usage.py
import shutil
total, used, free = shutil.disk_usage(".")
print(f"当前磁盘 总={total//1024**2}MB 已用={used//1024**2}MB 剩余={free//1024**2}MB")
运行效果(示例):
当前磁盘 总=466968MB 已用=312345MB 剩余=154623MB
八、打包与解包:make_archive / unpack_archive
python
# demo_archive.py
import shutil
import os
# 先准备些文件
os.makedirs("package/src", exist_ok=True)
for i in range(3):
with open(f"package/src/{i}.txt", "w") as f:
f.write(str(i))
# 打包
zip_path = shutil.make_archive("backup", "zip", "package")
print("打包完成:", zip_path)
# 解包
shutil.unpack_archive("backup.zip", "unpacked")
print("解包后文件:", sorted(os.listdir("unpacked/src")))
运行效果:
scss
打包完成: /absolute/path/backup.zip
解包后文件: ['0.txt', '1.txt', '2.txt']
九、权限与属主:chown(Unix 系统可见效果)
python
# demo_chown.py
import shutil
import os
import getpass
file = "own_me.txt"
with open(file, "w") as f:
f.write("test")
current_user = getpass.getuser()
try:
shutil.chown(file, user=current_user)
print("chown 成功,属主设为:", current_user)
except Exception as e:
print("chown 失败(Windows 或非 root):", e)
运行效果(Linux/macOS):
bash
chown 成功,属主设为: bronze
Windows 下:
bash
chown 失败(Windows 或非 root): [Errno 2] No such file or directory: ...
十、完整实战:一键备份脚本
功能:把指定目录打包成 zip,并自动加上时间戳。
python
# backup_tool.py
import shutil
import os
import datetime
def backup(src_dir, dst_dir="backups"):
os.makedirs(dst_dir, exist_ok=True)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
base_name = os.path.join(dst_dir, f"backup_{timestamp}")
archive_path = shutil.make_archive(base_name, "zip", src_dir)
print("备份成功 ->", archive_path)
if __name__ == "__main__":
os.makedirs("my_project", exist_ok=True)
with open("my_project/main.py", "w") as f:
f.write("# main\n")
backup("my_project")
运行效果:
bash
备份成功 -> backups/backup_20250817_213050.zip
小结
武器 | 用途 | 一句话记忆 |
---|---|---|
shutil.copy / copy2 | 复制文件 | copy2 带元数据 |
shutil.copytree | 复制目录 | 递归克隆 |
shutil.move | 移动 / 重命名 | 一切皆 move |
shutil.rmtree | 删目录 | 比 rm -rf 更 Pythonic |
shutil.make_archive | 打包 | zip / tar / gztar / bztar / xztar |
shutil.unpack_archive | 解包 | 自动识别格式 |
shutil.disk_usage | 看磁盘 | 返回三元组 |
shutil.which | 找命令 | PATH 里搜可执行文件 |
如果这篇文章帮到了你,欢迎请我喝一杯咖啡☕️,点击下面的【喜欢作者】按钮 进行打赏,让我继续熬夜码字!
最后感谢阅读!欢迎关注我,微信公众号: 倔强青铜三 。欢迎 点赞、收藏、关注,一键三连!!