苦练Python第66天:文件操作终极武器!shutil模块完全指南

196 阅读4分钟

前言

大家好,我是 倔强青铜三。欢迎关注我,微信公众号: 倔强青铜三。点赞、收藏、关注,一键三连!

今天咱们把 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 秒完成首次文件复制

# 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)

运行效果:

复制成功: demo_dir/hello_copy.txt

三、整目录克隆:copytree

# 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"))

运行效果:

目录树复制完成,dst_tree 存在文件: ['a.txt']

四、移动大法:shutil.move

# 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")])

运行效果:

移动后当前目录文件: ['move_me.txt']

五、彻底删除:rmtree

# 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"))

运行效果:

trash_dir 存在? False

六、查找系统命令:which

# demo_which.py
import shutil

python_path = shutil.which("python3") or shutil.which("python")
print("python 可执行文件路径:", python_path)

运行效果(示例,按机器实际路径):

python 可执行文件路径: /usr/bin/python3

七、磁盘用量查询:disk_usage

# 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

# 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")))

运行效果:

打包完成: /absolute/path/backup.zip
解包后文件: ['0.txt', '1.txt', '2.txt']

九、权限与属主:chown(Unix 系统可见效果)

# 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):

chown 成功,属主设为: bronze

Windows 下:

chown 失败(Windows 或非 root): [Errno 2] No such file or directory: ...

十、完整实战:一键备份脚本

功能:把指定目录打包成 zip,并自动加上时间戳。

# 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")

运行效果:

备份成功 -> 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 里搜可执行文件

如果这篇文章帮到了你,欢迎请我喝一杯咖啡☕️,点击下面的【喜欢作者】按钮 进行打赏,让我继续熬夜码字!

最后感谢阅读!欢迎关注我,微信公众号: 倔强青铜三
欢迎 点赞、收藏、关注,一键三连!!