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

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

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

相关推荐
Leinwin10 小时前
Claude 四月宕机七次:从一次事故看企业级 AI 部署的容灾设计
后端·python·flask
棉猴10 小时前
Python海龟绘图之绘制文本
javascript·python·html·write·turtle·海龟绘图·输出文本
渣渣盟10 小时前
大数据技术栈全景图:从零到一的入门路线(深度实战版)
大数据·hadoop·python·flink·spark
何陋轩10 小时前
Claude 3.5 vs GPT-4o vs Gemini:程序员应该选哪个?代码能力全面测评
人工智能·面试·架构
沪漂阿龙在努力10 小时前
人工智能核心—大语言模型技术解密,从入门到精通(全攻略)
人工智能
AI医影跨模态组学10 小时前
如何将深度学习超声影像特征与乳腺癌腋窝淋巴结治疗响应的生物学机制建立关联,并进一步解释其预测pCR与个体化治疗的机制联系
人工智能·深度学习·论文·医学·医学影像·影像组学·医学科研
机器人零零壹10 小时前
对话越擎科技CEO:iRobotCAM如何破解具身智能研发设计工具链难题
人工智能·机器人·工业软件·离线编程·irobotcam
大连好光景10 小时前
《AI百通系列》
人工智能
400分10 小时前
Claude Code 进阶使用:Subagents、第三方插件、Hooks、记忆与工作流
人工智能