苦练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 里搜可执行文件

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

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

相关推荐
用户0332126663675 分钟前
Python 实用技巧:从零自主生成结构化 PDF 页面
python
benchmark_cc7 分钟前
前复权数据每天可能变化,历史数据库应该覆盖还是保留原始价格?
大数据·python·pandas·量化交易·股票数据·quantdash
AI闲人11 分钟前
Jev 们不缺判断力,缺的是你的标准
人工智能·数字化·企业ai落地·语义层
计算机编程指导师20 分钟前
计算机毕设选题推荐:Hadoop大数据下的个体肥胖健康风险评估与可视化系统源码 毕业设计 毕设选题 数据分析 机器学习
大数据·hadoop·python·spark·毕业设计·课程设计·肥胖健康风险
code2cat24 分钟前
【随笔】MCP输入Schema:把参数错误拦在工具执行之前
python·json schema·ai agent·mcp
Pin_Qing33 分钟前
速度正式单独收费:OpenAI GPT-6.1 Sol Ultrafast上线,8倍速、6倍价,开发者该怎么选?
人工智能
m0_7156744334 分钟前
数据分类分级的范式转换:从规则匹配到场景化高准确率一键部署
大数据·网络·人工智能·网络安全
计算机编程指导师35 分钟前
Python大数据毕设怎么写?Django结合Hadoop+Spark京东销售分析系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习
大数据·hadoop·python·spark·毕业设计·课程设计·京东商品
源梦倩影41 分钟前
我把 YuanPlan 开源了:让任务、项目文档和 AI 协作在同一个地方发生
人工智能
合尘猫41 分钟前
AI 项目上线就停:一次事件循环阻塞的完整排查过程
人工智能·后端·python