Python内置模块:shutil模块使用教程(文件与目录高级操作实践)

Python内置模块:shutil模块使用教程(文件与目录高级操作实践)

编码文章call10242025-07-29 18:19:373A+A-

一、shutil模块简介

在Python开发中,文件与目录操作是最基础的需求之一。虽然os模块提供了基础的文件系统交互能力,但对于复制、移动、删除目录归档压缩等复杂操作,shutil模块(Shell Utility)提供了更高效、更安全的解决方案。


二、知识体系

shutil模块的功能可分为四大类:文件复制/移动/删除目录操作归档与压缩高级工具。以下是知识导图:

注:导图为使用Mermaid语法制作


三、核心功能

3.1 文件操作:复制、移动与删除

3.1.1 复制文件:shutil.copyfile(src, dst[, buffer_size])

  • 定义与原理
    copyfile用于复制文件内容(不复制元数据,如修改时间、权限)。它通过读取源文件的二进制流,并写入目标文件实现复制。
    • src:源文件路径(需存在);
    • dst:目标文件路径(若为目录则自动命名为同名文件;若为文件则覆盖);
    • buffer_size:缓冲区大小(默认1MB,影响复制速度)。
  • 要点与技巧
    • 仅复制文件内容,不保留元数据(如需保留元数据用copy2);
    • 目标路径的父目录需存在,否则抛出FileNotFoundError
    • 支持大文件复制(通过调整buffer_size优化内存占用)。
  • 示例代码
import shutil
import os

# 源文件路径(假设存在test_source.txt)
src_file = "data/source/test_source.txt"

# 目标路径(文件):覆盖或新建
dst_file1 = "data/dest/test_copy1.txt"

# 目标路径(目录):自动命名
dst_dir = "data/dest_dir/"
dst_file2 = os.path.join(dst_dir, os.path.basename(src_file))  # 结果:data/dest_dir/test_source.txt

# 创建目标目录(若不存在)
os.makedirs(dst_dir, exist_ok=True)

# 执行复制(缓冲区设为2MB)
shutil.copyfile(src_file, dst_file1, buffer_size=2*1024*1024)
shutil.copyfile(src_file, dst_file2)
print(f"复制成功!源文件大小:{os.path.getsize(src_file)} bytes")
print(f"目标文件1大小:{os.path.getsize(dst_file1)} bytes")
print(f"目标文件2大小:{os.path.getsize(dst_file2)} bytes")

3.1.2 复制文件并保留元数据:shutil.copy2(src, dst)

  • 定义与原理
    copy2copyfile的增强版,除了复制文件内容外,还会尝试复制源文件的元数据(如修改时间、访问时间、权限)。元数据通过os.stat()获取,并通过os.utime()os.chmod()设置。
  • 注意事项
    • 元数据复制可能受系统限制(如Windows不支持所有Unix权限);
    • 若目标文件已存在,会覆盖其内容但保留原元数据中的修改时间(需手动同步)。
  • 示例对比(copy vs copy2
  • 函数 复制内容 保留元数据 适用场景 copyfile 仅文件内容 不保留 临时文件复制 copy 内容+部分元数据(如权限) 部分保留 简单文件备份 copy2 内容+完整元数据 尽可能保留 需严格同步的文件复制
# 测试copy与copy2的元数据差异
src = "test_source.txt"
dst_copy = "test_copy.txt"
dst_copy2 = "test_copy2.txt"
shutil.copy(src, dst_copy)
shutil.copy2(src, dst_copy2)

# 查看修改时间(原文件修改后复制)
import time
print("原文件修改时间:", time.ctime(os.path.getmtime(src)))
print("copy目标修改时间:", time.ctime(os.path.getmtime(dst_copy)))   # 可能与原文件不同

print("copy2目标修改时间:", time.ctime(os.path.getmtime(dst_copy2))) # 接近原文件时间

3.1.3 移动文件/目录:shutil.move(src, dst)

  • 定义与原理
    move用于移动文件或目录(本质是重命名或跨文件系统复制+删除)。若目标路径存在且为目录,则源文件会被移动到该目录下(同名则覆盖);若为目标文件,则覆盖。
  • 要点与技巧
    • 跨文件系统(如从C盘到D盘)时,move会先复制再删除源文件;
    • 移动目录时需确保目标目录不存在(否则抛出FileExistsError);
    • 建议配合os.replace()理解底层逻辑(shutil.move内部调用os.renameos.replace)。
  • 示例代码
src_dir = "data/source_dir"
dst_dir = "data/dest_dir"

# 移动目录(目标不存在时)
shutil.move(src_dir, dst_dir)
print(f"目录已移动至:{os.path.abspath(dst_dir)}")

# 移动文件到已有目录(自动命名)
src_file = "data/temp.txt"
shutil.move(src_file, dst_dir)  # 结果:data/dest_dir/temp.txt

3.1.4 删除文件

shutil 模块没有专门删除单个文件的函数,应使用 os 模块的 remove() 函数:os.remove(file_path)。


3.2 目录操作:复制、删除与移动

3.2.1 递归复制目录:shutil.copytree(src, dst[, dirs_exist_ok=False])

  • 定义与原理
    copytree用于递归复制整个目录树(包括子目录和文件)。默认情况下,目标目录dst不能存在,否则抛出FileExistsError(Python 3.8+支持dirs_exist_ok=True允许目录存在并合并内容)。
  • 参数详解
    • symlinks:是否复制符号链接(默认False,即复制目标文件而非链接);
    • ignore:忽略特定文件/目录(传入可调用对象,参数为当前目录路径和文件列表,返回忽略列表);
    • copy_function:自定义复制函数(默认shutil.copy2)。
  • 示例代码(含忽略规则)
src_dir = "data/project"
dst_dir = "data/project_backup"

# 忽略.git目录和*.tmp文件
def ignore_rules(dirpath, names):
    ignored = []
    if ".git" in names:
        ignored.append(".git")
    for name in names:
        if name.endswith(".tmp"):
            ignored.append(name)
    return ignored

# 复制目录(Python 3.8+支持dirs_exist_ok)
shutil.copytree(
    src_dir,
    dst_dir,
    dirs_exist_ok=True,  # 允许目标目录存在(合并内容)
    ignore=ignore_rules,
    copy_function=shutil.copy2  # 保留元数据
)

3.2.2 递归删除目录:shutil.rmtree(path[, ignore_errors=False, onerror=None])

  • 定义与原理
    rmtree用于递归删除非空目录(通过调用os.unlink()删除文件,os.rmdir()删除空目录)。
  • 注意事项
    • 危险操作!删除前务必确认路径(可先打印os.listdir(path)确认内容);
    • ignore_errors=True会忽略所有错误(如权限不足),但不建议生产环境使用;
    • onerror可自定义错误处理(如记录日志后重试)。
  • 示例(安全删除)
dir_to_remove = "data/temp_dir"

# 安全检查:确认目录存在且非空
if os.path.isdir(dir_to_remove) and os.listdir(dir_to_remove):
    try:
        shutil.rmtree(dir_to_remove)
        print(f"目录删除成功:{dir_to_remove}")
    except PermissionError as e:
        print(f"删除失败(权限不足):{e}")
else:
    print("目录不存在或为空,无需删除")

3.3 归档与压缩:打包与解包

shutil支持常见的归档格式(如ZIP、TAR),通过make_archiveunpack_archive实现。

3.3.1 创建归档:shutil.make_archive(base_name, format[, root_dir=None, ...])

  • 定义与原理
    make_archive用于将目录或文件打包为指定格式的归档文件(如ZIP、TAR.GZ)。
  • 参数详解
    • base_name:归档文件的基础名称(不含扩展名,如data/backup会生成backup.zip);
    • format:归档格式(ziptargztarbztarxztar);
    • root_dir:要打包的根目录(默认当前目录);
    • owner/group:Unix系统下的所有者和组(默认保留原信息);
    • compress:压缩算法(仅对部分格式有效,如gzip对应gztar)。
  • 示例(打包为ZIP)
# 打包data/project目录为project_20250714.zip
base_name = "project_20250714"
format = "zip"
root_dir = "data/project"

# 生成ZIP文件(自动保存在当前目录)
archive_path = shutil.make_archive(
    base_name,
    format=format,
    root_dir=root_dir,
    compress="zip"  # 显式指定压缩算法(可选)
)
print(f"归档文件已生成:{archive_path}")  # 输出:project_20250714.zip

3.3.2 解包归档:shutil.unpack_archive(filename[, extract_dir=None, format=None])

  • 定义与原理
    unpack_archive用于解压归档文件到指定目录。
  • 示例(解压ZIP)
archive_file = "project_20250714.zip"
extract_dir = "data/extracted_project"

# 解压到指定目录(自动创建目录)
shutil.unpack_archive(
    filename=archive_file,
    extract_dir=extract_dir,
    format="zip"  # 可选(自动识别时可不写)
)
print(f"归档解压完成,路径:{extract_dir}")

3.4 高级工具:元数据处理与路径查找

3.4.1 复制文件元数据:shutil.copystat(src, dst)

  • 定义与原理
    copystat用于复制源文件的元数据(如修改时间、访问时间、权限)到目标文件或目录。常用于copy2的底层实现。
  • 示例
src = "test_source.txt"
dst = "test_copied.txt"
shutil.copyfile(src, dst)  # 仅复制内容
shutil.copystat(src, dst)  # 复制元数据(修改时间、权限等)

3.4.2 查找可执行文件路径:shutil.which(cmd)

  • 定义与原理
    which用于在系统环境变量PATH中查找可执行文件的绝对路径(类似Unix的which命令)。
  • 示例
# 查找python3的路径
python_path = shutil.which("python3")
print(f"python3路径:{python_path}")  # 输出:/usr/bin/python3(或其他系统路径)

四、应用示例

案例1:自动化文件备份脚本

需求:每天将/var/log目录下的日志文件备份到/backup/logs,保留最近7天的备份。

实现思路

  1. 检查备份目录是否存在,不存在则创建;
  2. 使用copytree复制/var/log/backup/logs/$(date +%Y%m%d)
  3. 清理超过7天的旧备份。

代码示例

import shutil
import os
import time
from datetime import datetime, timedelta

def backup_logs():
    src_dir = "/var/log"
    backup_root = "/backup/logs"
    
    # 创建备份根目录
    os.makedirs(backup_root, exist_ok=True)
    
    # 生成今日备份目录名(如20250714)
    today = datetime.now().strftime("%Y%m%d")
    today_backup = os.path.join(backup_root, today)
    
    # 复制日志目录(覆盖已有备份)
    try:
        shutil.copytree(src_dir, today_backup, dirs_exist_ok=True)
        print(f"今日备份成功:{today_backup}")
    except Exception as e:
        print(f"备份失败:{e}")
        return
    
    # 清理7天前的备份
    cutoff_time = time.time() - 7 * 86400  # 7天的秒数
    for dir_name in os.listdir(backup_root):
        dir_path = os.path.join(backup_root, dir_name)
        if os.path.isdir(dir_path):
            # 获取目录修改时间(备份完成时间)
            mtime = os.path.getmtime(dir_path)
            if mtime < cutoff_time:
                shutil.rmtree(dir_path)
                print(f"清理旧备份:{dir_path}")

if __name__ == "__main__":
    backup_logs()

案例2:整理下载目录(按文件类型分类)

需求:将~/Downloads目录下的文件按类型(图片、文档、压缩包)移动到子目录ImagesDocumentsArchives

实现思路

  1. 定义文件类型与目标目录的映射(如.jpgImages);
  2. 遍历Downloads目录下的所有文件;
  3. 根据扩展名判断目标目录,移动文件(跳过已存在的目录)。

代码示例

import shutil
import os
from pathlib import Path

def organize_downloads():
    download_dir = Path.home() / "Downloads"
    # 文件类型映射(扩展名→目标目录名)
    type_map = {
        "jpg": "Images",
        "png": "Images",
        "pdf": "Documents",
        "docx": "Documents",
        "zip": "Archives",
        "tar.gz": "Archives"
    }
    
    # 创建目标目录(若不存在)
    for dir_name in type_map.values():
        target_dir = download_dir / dir_name
        os.makedirs(target_dir, exist_ok=True)
    
    # 遍历下载目录的文件(跳过子目录)
    for file_path in download_dir.iterdir():
        if file_path.is_file():
            # 获取文件扩展名(转为小写)
            ext = file_path.suffix[1:].lower()  # 去掉点,如"jpg"
            # 查找匹配的目标目录
            target_dir_name = next(
                (name for ext_pattern, name in type_map.items() if ext == ext_pattern),
                "Others"  # 未匹配的归为Others
            )
            target_dir = download_dir / target_dir_name
            
            # 移动文件(避免覆盖,若存在则重命名)
            target_path = target_dir / file_path.name
            if target_path.exists():
                # 重命名(如file.jpg→file_1.jpg)
                base, ext = os.path.splitext(file_path.name)
                counter = 1
                while True:
                    new_name = f"{base}_{counter}{ext}"
                    new_path = target_dir / new_name
                    if not new_path.exists():
                        target_path = new_path
                        break
                    counter += 1
            
            shutil.move(str(file_path), str(target_path))
            print(f"移动文件:{file_path} → {target_path}")

if __name__ == "__main__":
    organize_downloads()

五、扩展学习:结合其他模块应用

5.1 与os模块协同

shutil依赖os模块处理路径和基础文件操作,例如:

  • os.path.exists()检查路径是否存在;
  • os.makedirs()创建多级目录;
  • os.path.getsize()获取文件大小(验证复制完整性)。

5.2 日志记录与异常处理

生产环境中,建议使用logging模块记录操作日志,并捕获shutil可能抛出的异常(如OSErrorPermissionError):

import logging

logging.basicConfig(filename="shutil_ops.log", level=logging.INFO)

try:
    shutil.copytree("src", "dst")
    logging.info("目录复制成功")
except Exception as e:
    logging.error(f"目录复制失败:{str(e)}")

5.3 异步操作优化

对于大文件或大量文件的复制,可使用asyncio配合aiofiles实现异步IO,提升效率(需Python 3.7+):

import asyncio
import aiofiles

async def async_copyfile(src, dst, buffer_size=1024*1024):
    async with aiofiles.open(src, "rb") as f_src:
        async with aiofiles.open(dst, "wb") as f_dst:
            while chunk := await f_src.read(buffer_size):
                await f_dst.write(chunk)

# 使用示例
asyncio.run(async_copyfile("large_file.zip", "backup_large_file.zip"))

六、总结

6.1 学习路线图

6.2 学习总结

  • 核心函数copyfile/copy2(文件复制)、copytree(目录复制)、move(移动)、rmtree(删除目录)、make_archive(归档);
  • 注意事项:目标路径父目录需存在、目录复制不可覆盖、元数据复制需用copy2
  • 最佳实践:优先使用copy2保留元数据、大文件操作使用缓冲区、生产环境添加日志和异常处理。

通过本教程,我们能够使用shutil模块完成日常文件操作需求,并能根据场景扩展功能。建议结合实际项目练习(如日志备份、文件整理脚本),加深理解!


持续更新Python编程学习日志与技巧,敬请关注!


#编程# #学习# #python# #在头条记录我的2025#


点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4