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

前言

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

今天咱们把 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 里搜可执行文件

如果这篇文章帮到了你,欢迎请我喝一杯咖啡☕️,点击下面的【喜欢作者】按钮 进行打赏,让我继续熬夜码字!
最后感谢阅读!欢迎关注我,微信公众号: 倔强青铜三

欢迎 点赞、收藏、关注,一键三连!!

相关推荐
倔强青铜三2 小时前
苦练Python第65天:CPU密集型任务救星!多进程multiprocessing模块实战解析,攻破GIL限制!
人工智能·python·面试
Panda__Panda2 小时前
docker项目打包演示项目(数字排序服务)
运维·javascript·python·docker·容器·c#
强哥之神2 小时前
浅谈目前主流的LLM软件技术栈:Kubernetes + Ray + PyTorch + vLLM 的协同架构
人工智能·语言模型·自然语言处理·transformer·openai·ray
zskj_qcxjqr2 小时前
七彩喜艾灸机器人:当千年中医智慧遇上现代科技
大数据·人工智能·科技·机器人
怪兽20143 小时前
SQL优化手段有哪些
java·数据库·面试
Lris-KK3 小时前
力扣Hot100--94.二叉树的中序遍历、144.二叉树的前序遍历、145.二叉树的后序遍历
python·算法·leetcode
Zack_Liu3 小时前
深度学习基础模块
人工智能·深度学习
zy_destiny4 小时前
【工业场景】用YOLOv8实现抽烟识别
人工智能·python·算法·yolo·机器学习·计算机视觉·目标跟踪
狠活科技4 小时前
免登录!免安装ClI,Claude Code官方插件接入API使用教程
人工智能·vscode·ai编程