一、基础概念
shutil(shell utility)是python标准库,用于 处理文件 / 目录 / 归档的高级操作 的模块。
它建立在 os 模块之上,屏蔽了平台差异(Windows和POSIX)。os 模块偏向底层文件操作,shutil 封装了更上层能力:复制、移动、删除目录、打包压缩、获取磁盘空间等。
# 导入模块
import shutil
1.1、为什么文件操作推荐优选 shutil 而不是 os
1.1.1、os 模块的“半成品”状态
os 模块当然很重要,它提供了文件系统操作的底层接口,比如 os.rename() 只能重命名或移动同一文件系统内的文件, os.remove() 只能删单个文件, os.listdir() 只能列出目录下的名字。如果你要复制一个文件, os 模块本身根本没有直接的复制函数,你只能自己打开源文件、读取内容、再写到目标文件。这还只是单个文件的复制,要是递归复制整个目录树,我见过有人用 os.walk 配合 os.mkdir 加 open 写循环,代码量轻松破百行,而且边界情况(比如源目录里有符号链接、目标目录已存在)处理起来特别痛苦。
1.1.2、shutil 的定位:把高级操作封装好
shutil 模块的全称是 shell utilities,从名字就能看出它的定位——它提供的是更接近 shell 命令行为的高级文件操作。比如 shutil.copy 类似于 cp , shutil.move 类似于 mv , shutil.rmtree 类似于 rm -rf , shutil.copytree 类似于 cp -r , shutil.make_archive 类似于 tar 或 zip 命令。这意味着你不需要自己处理递归遍历、跨文件系统判断、元数据复制等细节,一个函数调用就搞定了。
我在实际项目里最深的感受是:用 os 写文件操作,你得自己记住“要处理哪些边界情况”;用 shutil ,标准库作者已经帮你把这些边界情况都处理好了。比如 shutil.move 会判断目标路径是否跨文件系统,跨了就自动复制加删除,不跨就直接 rename,这个判断逻辑如果自己写,至少得几十行,还容易遗漏。
1.1.3、跨平台能力是 shutil 的隐藏优势
很多开发者在 Windows 上写完脚本,部署到 Linux 服务器上就出问题。 os 模块的部分函数在不同平台上的行为差异很微妙,比如路径分隔符、权限模型、文件属性。 shutil 在设计上就尽量把平台差异封装在内部,比如复制权限位、检查可执行文件( shutil.which )等功能,在 Windows、macOS、Linux 上都能用同一套 API 实现相同的目的。我在帮朋友处理一个跨平台的构建脚本时,就是靠 shutil.copy2 替换了原来调系统命令 cp 的逻辑,才让脚本从 Linux 直接平移到 Windows 而不需要改代码。
二、shutil主要模块
| 分类 | 主要 API |
|---|---|
| 文件复制 | copyfileobj,copyfile,copymode,copystat,copy,copy2 |
| 目录操作 | copytree,rmtree,move,ignore_patterns |
| 磁盘/权限 | disk_usage,chown |
| 归档打包 | make_archive,unpack_archive,get_archive_formats,register_* |
| 杂项工具 | which,get_terminal_size |
| 异常体系 | shutil.Error,shutil.SameFileError,shutil.SpecialFileError |
2.1、文件复制
| 函数 | 复制内容 | 目标目录要求 | 返回值 | 适用场景 |
|---|---|---|---|---|
| shutil.copyfileobj(fsrc, fdst, length) | 文件对象内容 | 文件对象已打开 | 无 | 需要自定义缓冲区、从网络流或内存流复制 |
| shutil.copyfile(src, dst) | 文件内容 | 目标目录必须存在 | 目标路径字符串 | 只关心文件内容,不关心权限和时间 |
| shutil.copy(src, dst) | 文件内容 + 权限位 | 目标目录必须存在 | 目标路径字符串 | 需要保留可执行权限,比如复制脚本 |
| shutil.copy2(src, dst) | 文件内容 + 权限位 + 元数据(修改时间、访问时间) | 目标目录必须存在 | 目标路径字符串 | 需要保留文件的修改时间,做备份和同步 |
2.1.1、shutil.copyfile(src, dst, *, follow_symlinks=True)
作用:只复制文件内容,不复制文件元信息(权限、修改时间)
- src:源文件路径(字符串 / Path)
- dst:目标文件路径,不能是文件夹,如果 dst 已存在,会直接覆盖
- follow_symlinks=True:True 跟随软链接(复制链接指向的真实文件);False 复制软链接本身
返回:目标文件路径字符串
注意:
copyfile不能传目录!目标如果是目录会报错- 如果 src 和 dst 不能是同一个文件,否则抛
SameFileError - 如果 dst 不可写,抛 OSError
- 如果 follow_symlinks=False 且 src 是符号链接,则创建新的符号链接而非复制内容
import shutil
# 复制 source.txt 到 target.txt,如果target.txt存在,则覆盖target.txt
src = "files/source.txt"
dst = "files/target.txt"
with open(src, 'w', encoding='utf-8') as f:
f.write("Hello World")
shutil.copyfile(src, dst)
- 生产安全封装,防止源文件不存在
import os
import shutil
src = "files/source.txt"
dst = "files/target.txt"
def copy_file(source_file: str, target_file: str):
if not os.path.isfile(source_file):
raise FileNotFoundError(f"源文件不存在: {source_file}")
if os.path.isfile(target_file):
print(f"警告:目标文件{target_file}已存在,将会覆盖")
try:
shutil.copyfile(source_file, target_file)
except FileNotFoundError as fnf:
print("源文件不存在", fnf)
except shutil.SameFileError as sf:
print("源和目标是同一文件,不可复制", sf)
except PermissionError as pe:
print("权限不足", pe)
copy_file(src, dst)
2.1.2、shutil.copy(src, dst, *, follow_symlinks=True)
作用:复制文件内容 + 文件权限(mode),不复制文件创建 / 修改时间等其他元数据
- 如果 dst 是已存在的目录,文件会被复制到 dst/同名文件 下
- 如果 dst 是文件路径,则覆盖该文件
- 底层调用
copyfile+copymode
import os, shutil
# 目标是文件路径
shutil.copy("a.txt", "backup_a.txt")
# 目标是文件夹,自动在文件夹内生成同名文件
os.mkdir("backup_dir")
shutil.copy("a.txt", "backup_dir") # 结果 backup_dir/a.txt
# 批量部署静态资源,保留可执行位
for f in ['start.sh', 'stop.sh', 'health.sh']:
shutil.copy(f, '/opt/app/bin/')
2.1.3、shutil.copy2 (src, dst, *, follow_symlinks=True) ✅【最常用单文件复制】
作用:复制文件内容 + 完整元数据(权限、修改时间、访问时间),适合做文件备份
- 区别:
copy只复制权限;copy2尽可能保留文件所有信息 - 限制:Windows 上部分文件元数据无法完整还原
- 相当于
copyfile+copystat
import shutil, os
from datetime import datetime
shutil.copy2('source.log', 'archive/source.log')
src_stat = os.stat('source.log')
dst_stat = os.stat('archive/source.log')
print('mtime 是否一致:', src_stat.st_mtime == dst_stat.st_mtime) # True
2.1.4、shutil.copymode(src, dst, *, follow_symlinks=True)
作用:只复制文件权限(mode),不动内容、不动时间戳
- 只修改目标文件的读写执行权限,文件内容完全不变
- Linux 下效果明显,Windows 权限模型不一样,效果有限
import shutil, os, stat
# 将 b.txt 的权限改成和 a.txt 一样,不改动b.txt内容
shutil.copymode("a.txt", "b.txt")
# 脚本部署时保留可执行权限
shutil.copyfile('deploy.sh', '/opt/app/deploy.sh')
shutil.copymode('deploy.sh', '/opt/app/deploy.sh')
print(oct(os.stat('/opt/app/deploy.sh').st_mode & 0o777)) # 例如 0o755
2.1.5、shutil.copystat(src, dst, *, follow_symlinks=True)
作用:复制权限 + 访问时间、修改时间;不复制文件内容
- copymode:仅复制权限
- copystat:复制权限 + atime/mtime
复制所有 stat 元数据:权限位、最后访问时间、最后修改时间、flags(若支持)。不复制内容
import shutil, os
from datetime import datetime
# 案例:让 dst 的 mtime 与 src 完全一致(常用于构建产物复现)
shutil.copyfile('template.html', 'output.html')
shutil.copystat('template.html', 'output.html')
st = os.stat('output.html')
print('mtime =', datetime.fromtimestamp(st.st_mtime))
2.1.6、shutil.copyfileobj(fsrc, fdst, length=0)
作用:把已打开的文件对象内容复制到另一个文件对象
特点:只处理文件对象,不处理路径、不处理元数据
length:是缓冲区大小(0 表示用默认大小,通常是 64KB 或系统块大小)。这是所有复制函数的底层实现
import shutil
# 大文件流式复制,避免一次性读入内存
with open('big_source.iso', 'rb') as fsrc, open('big_copy.iso', 'wb') as fdst:
shutil.copyfileobj(fsrc, fdst, length=1024 * 1024) # 1MB 缓冲
# 给复制进度做回调
def copy_with_progress(src, dst, buf_size=1024 * 1024):
total = 0
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
while True:
buf = fsrc.read(buf_size)
if not buf:
break
fdst.write(buf)
total += len(buf)
print(f'\r已复制: {total / 1024 / 1024:.2f} MB', end='')
print()
copy_with_progress('big_source.iso', 'big_copy.iso')
2.2、目录操作
2.2.1、shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False, dirs_exist_ok=False)
作用:递归复制整个目录树(文件夹 + 里面所有子文件夹、文件)
- src:源目录,必须存在且是文件夹
- dst:目标目录,默认不能预先存在,否则报错;
dirs_exist_ok=True允许目标目录已存在(Python3.8+) - symlinks=False:默认把软链接指向的真实文件复制;symlinks=True,则只复制软链接本身,不复制真实文件
- copy_function:指定复制文件的函数,默认 copy2(保留元数据)
- ignore_dangling_symlinks:忽略失效软链接
- ignore:回调函数,过滤不需要复制的文件,返回要忽略的文件名列表。两种使用方法:
- 1、配合 shutil.ignore_patterns(*patterns) 使用
- 2、自定义回调函数:ignore 回调签名:ignore(src_dir, names),src_dir:源目录, names:源目录下
os.listdir的结果
import shutil
source_dir = '/path/to/static'
target_dir = '/path/to/static_bak'
# 第一种:基础复制整个文件夹
# 把 static 整个目录复制到 static_bak,注意:static_bak 目录是不存在的
shutil.copytree(source_dir, target_dir)
# 第二种:复制文件夹内容到已存在文件夹
# static_bak 目标目录已存在也能复制,做增量合并
shutil.copytree(source_dir, target_dir, dirs_exist_ok=True)
- ignore 过滤:过滤并不需要复制的文件
# 第一种:配合 shutil.ignore_patterns(*patterns) 使用
shutil.copytree(source_dir, target_dir, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'), dirs_exist_ok=True)
# 第二种:自定义回调函数
# 过滤规则:根据实际情况 自定义适合的规则
def ignore_files(src_path, filenames):
ignore_list = []
for name in filenames:
# 规则一:按照文件大小过滤
file_path = os.path.join(src_path, name)
if os.path.isfile(file_path) and os.path.getsize(file_path) > 100 * 1024 * 1024:
ignore_list.append(name)
# 规则二:按照文件名称过滤掉.log文件、test_开头的文件和包含temp的文件
if name.endswith('.log') or name.startswith('test_') or 'temp' in name:
ignore_list.append(name)
return ignore_list
shutil.copytree(source_dir, target_dir, ignore=ignore_files, dirs_exist_ok=True)
- 符号链接处理
import shutil
# 直接复制软链接本身,不拷贝链接指向的文件
shutil.copytree("source_folder", "target_folder", symlinks=True)
# 跟随链接(把目标内容复制过去)
shutil.copytree("source_folder", "target_folder", symlinks=False)
2.2.2、shutil.rmtree(path, ignore_errors=False, οnerrοr=None, *, onexc=None)
作用:递归删除整个目录(文件夹 + 里面所有子目录、文件),删除后不可恢复!
- path:
要删除的目录,不能是普通文件 - ignore_errors=False:True 忽略删除时所有错误(
适合清理临时目录);False 直接抛出异常 - onerror:错误回调函数,自定义错误处理(
生产推荐使用,不要直接 ignore_errors)- 3.12版本以下用onerror,3.12+用onexc
注意:
- 如果 path 是符号链接,会抛 OSError ——只能删除真实目录
- 删除只读文件在 Windows 上可能失败,需要处理
- rmtree
不能用于普通文件;如果 path 是文件会报错;生产务必校验路径,防止误删根目录! os.rmdir()只能删除空文件夹;shutil.rmtree可以删除非空文件夹
import os, shutil
target_dir = '/tmp/to/static'
# 第一种:基础删除整个 static 文件夹
shutil.rmtree(target_dir)
# 第二种:忽略删除时的权限错误,只适合清理临时垃圾目录
shutil.rmtree(target_dir, ignore_errors=True)
# 第三种:安全删除,生产务必校验路径,防止误删根目录!
# print(os.path.expanduser('~')) 用户家目录:/home/用户名
def safe_rmtree(path):
if not path or path in ('/', "/home", os.path.expanduser('~')):
raise ValueError(f'拒绝删除危险路径: {path}')
if not os.path.isdir(path):
raise NotADirectoryError("Target path is not a directory")
shutil.rmtree(path)
safe_rmtree(target_dir)
# 第四种:只删除/tmp下的临时目录
del_dir = "/tmp/test_dir"
if os.path.isdir(del_dir) and del_dir.startswith("/tmp/"):
shutil.rmtree(del_dir)
else:
raise Exception("路径非法,禁止删除")
- 自定义错误回调处理
import shutil, os, stat
target_dir = '/tmp/to/static'
def error_handler(func, path, exc_info):
print(f"删除失败: {path}, 函数:{func}, 异常:{exc_info}")
shutil.rmtree(target_dir, onerror=error_handler)
# Python 3.12+ 用 onexc
def on_exc(func, path, exc):
# 遇到只读文件:先改权限再重试
os.chmod(path, stat.S_IWRITE)
func(path)
shutil.rmtree(target_dir , onexc=on_exc)
# Python < 3.12+ 用 onerror
def on_error(func, path, exc_info):
os.chmod(path, stat.S_IWRITE)
func(path)
shutil.rmtree(target_dir , onerror=on_error)
2.2.3、shutil.move(src, dst, copy_function=copy2)
作用:移动文件或文件夹,支持跨分区 / 文件系统 移动,类似 shell mv。也可以用于重命名
- src:源,可以是文件 / 文件夹
- dst:目标。如果 dst 是已存在目录,则把 src 移动进 dst 目录内
注意:
- 同磁盘分区 / 同文件系统:本质是重命名(
os.rename),速度极快 - 跨磁盘分区 / 跨文件系统:底层先复制全部内容(
走 copy_function),再删除源文件 - 如果 dst 是
已存在的目录,会把 src 移动到 dst 目录内 - 如果目标文件已存在,则会直接覆盖
import os, shutil
dst = "path/"
# 第一种:文件重命名
shutil.move("source.txt", "source_new.txt")
# 第一种:移动文件到目标文件夹内
shutil.move("source.txt", dst)
# 第二种:移动文件到目标文件夹并重命名
shutil.move("source.txt", dst + "source.txt")
# 第三种:移动整个文件夹
shutil.move("static", "/data/static_new")
# 第四种:跨文件系统移动
shutil.move('/mnt/usb/report.pdf', '/data/report.pdf')
- 避免覆盖已有文件
# 第一种:
def move_no_overwrite(source_file, target_file):
if not os.path.exists(target_file):
raise FileExistsError(f'{dst} 已存在,拒绝覆盖')
shutil.move(source_file, target_file)
move_no_overwrite('a.txt', 'b.txt')
# 第二种:
def move_no_overwrite(source_file, target_file):
if not os.path.exists(source_file):
print(f"源文件不存在:{source_file}")
if not os.path.exists(target_file):
shutil.move(source_file, target_file)
else:
print(f"文件已存在:{target_file}")
move_no_overwrite('files/target.txt', 'files/target.txt')
2.2.4、shutil.ignore_patterns(*patterns)
作用:返回一个 ignore 回调,用于 copytree。支持 fnmatch 风格通配符(*、?、[seq])
import shutil
# 排除所有编译产物、日志、IDE 配置
ignore = shutil.ignore_patterns(
'*.pyc', '*.pyo', '__pycache__',
'*.log', '.idea', '.vscode', 'node_modules',
)
shutil.copytree('source', 'dist', ignore=ignore)
2.3、磁盘/权限
2.3.1、shutil.disk_usage(path)
作用:获取指定路径所在磁盘空间信息(总大小、已用、空闲),返回命名元组 (total, used, free),单位字节
import shutil, os
target_dir = 'D:\\'
usage = shutil.disk_usage(target_dir)
print(f"总量:{usage.total / 1024 / 1024 / 1024:.2f} GB")
print(f"已用:{usage.used / 1024 / 1024 / 1024:.2f} GB")
print(f"可用:{usage.free / 1024 ** 3:.2f} GB")
print(f"使用率:{(usage.used / usage.total) * 100:.2f}%")
# 备份 / 上传文件前检查剩余空间
def check_disk_space(path, required_space_gb):
if not os.path.exists(path):
# os.makedirs(path, exist_ok=True)
raise FileNotFoundError(f"提供的路径不存在: {path}")
available_space_gb = shutil.disk_usage(path).free / (1024 ** 3) # GB
if available_space_gb < required_space_gb:
raise OSError(f"磁盘空间不足。当前可用空间: {available_space_gb:.2f} GB, 要求空间: {required_space_gb} GB")
return True
2.3.2、shutil.chown(path, user=None, group=None)
作用:修改 文件 / 目录的 属主/ 属组
注意:
- 仅 Linux/macOS 可用,Windows 无效果
- user/group 接受
用户名/组名字符串 或uid/gid整数 - 通常需要
root权限
import shutil
# 用名字
shutil.chown("/data/file.txt", user="nginx", group="nginx")
# 用uid/gid
shutil.chown('/data/file', user=1000, group=1000)
# 只改组
shutil.chown('/data/file', group='developers')
2.4、归档打包
shutil 支持调用系统归档工具,支持 zip, tar, gztar, bztar, xztar 格式
2.4.1、shutil.make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=False, owner=None, group=None, logger=None)
作用:打包目录为压缩包
- base_name:目标压缩包文件名称,不带扩展名(会自动加)
- format:压缩包格式。zip / tar / gztar / bztar / xztar
- root_dir:要打包目录的根目录,打包前会先切换到这个目录,
不存在会直接抛异常 - base_dir:在
root_dir内部,要打包的子目录/文件 - dry_run:是否仅模拟运行。
dry_run=1只打印日志,不实际创建压缩包 - owner:tar 包专用:设置 tar 内文件的属主(用户名或 uid),Windows 无效
- group:tar 包专用:设置 tar 内文件的属组,Windows 无效
- logger:日志对象,传入 logging.Logger 实例,用来输出打包日志
返回值: 最终生成的压缩包完整路径
base_name参数 用来控制压缩包的存放路径
# 案例1:把整个 project/ 打成 zip → 生成 backup.zip
# base_name 也可以控制 压缩包 存放路径
archive = shutil.make_archive('/opt/backup', 'zip', root_dir='project')
print(archive) # /opt/backup.zip
archive = shutil.make_archive('/zkc/backup', 'zip', root_dir='project')
print(archive) # /zkc/backup.zip
# 案例2:只打包 project/src/ → 生成 src.tar.gz
shutil.make_archive('src_snapshot', 'gztar', root_dir='project', base_dir='src')
# 案例3:带时间戳的日志归档
from datetime import datetime
stamp = datetime.now().strftime('%Y%m%d_%H%M%S')
shutil.make_archive(f'/backup/logs_{stamp}', 'gztar', root_dir='/var/log', base_dir='app')
# 案例4:仅模拟运行,不实际创建压缩包
shutil.make_archive('preview', 'zip', root_dir='project', dry_run=1)
2.4.2、shutil.unpack_archive(filename, extract_dir=None, format=None, *, filter=None)
作用:自动识别格式解包(也可显式指定)
- extract_dir:默认当前目录
- filename:要解压的文件名
- format:显示指定压缩包格式
import shutil
import os, zipfile
from pathlib import Path
# 自动识别压缩包格式
shutil.unpack_archive('backup.zip', extract_dir='/tmp/restore')
# 显式指定格式(当扩展名不标准时)
shutil.unpack_archive('data.unknown', extract_dir='/tmp/data', format='gztar')
# 安全解包(防 Zip Slip 路径穿越)
def safe_unpack(archive_path, dest):
dest = Path(dest).resolve()
dest.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(archive_path) as zf:
for name in zf.namelist():
target = (dest / name).resolve()
if not str(target).startswith(str(dest)):
raise ValueError(f'非法路径: {name}')
zf.extractall(dest)
safe_unpack('upload.zip', '/tmp/uploads')
2.4.3、shutil.get_archive_formats()
print('可打包格式:')
for name, desc in shutil.get_archive_formats():
print(f' {name:8s} - {desc}')
2.4.4、shutil.get_unpack_formats()
print('\n可解包格式:')
for name, exts, desc in shutil.get_unpack_formats():
print(f' {name:8s} {exts} - {desc}')
2.5、其它工具
2.5.1、shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None)
作用:查找系统可执行程序路径,类似 shell which命令
import shutil
# 检查命令是否存在
for cmd in ['python3', 'git', 'docker', 'nonexistent_tool']:
path = shutil.which(cmd)
print(f'{cmd:20s} -> {path}')
# 在自定义路径里查找
print(shutil.which('node', path='/usr/local/bin:/opt/node/bin'))
# 工具链自动探测
def get_git():
git_path = shutil.which('git')
if not git_path:
raise RuntimeError('未找到 git,请先安装')
return git
print(get_git())
2.6、异常体系
| 异常 | 触发场景 |
|---|---|
| shutil.Error | copytree/rmtree 批量操作时收集的错误集合 |
| shutil.SameFileError | 源和目标指向同一个文件 |
| shutil.SpecialFileError | 试图复制 FIFO / 设备文件等特殊文件 |
| shutil.Errorcopytree | 批量操作,部分文件失败,汇总错误 |
| OSError / FileNotFoundError | 源不存在、权限不足 |
| PermissionError | 读写权限不足 |
| shutil.ExecError | 已弃用并在 3.12 移除 |
import shutil
# copytree 遇到多个错误时抛出 Error,内含错误列表
try:
shutil.copytree('a', 'b')
except shutil.Error as e:
for src, dst, msg in e.args[0]:
print(f' {src} -> {dst}: {msg}')
# 处理特殊文件
try:
shutil.copy2('/dev/null', '/tmp/x')
except shutil.SpecialFileError as e:
print('不支持特殊文件:', e)
# 错误处理模板
def safe_copy2(src, dst):
try:
shutil.copytree("src_dir", "dst_dir", dirs_exist_ok=True)
return True
except FileNotFoundError:
print(f'源文件不存在: {src}')
except shutil.SameFileError as e:
print("源和目标相同,跳过", e)
except shutil.Error as e:
print(f"部分文件复制失败:{e.args[0]}")
except PermissionError:
print("权限不足!")
except Exception as e:
print(f"未知异常:{repr(e)}")
return False
三、实际案例:
3.1、脚本一:自动备份目录脚本(1)
将源目录直接打压缩包后存放到目标路径
import os, shutil
from datetime import datetime
PROJECT_DIR = '/home/zkc/workspace/my_app'
BACKUP_ROOT = '/home/zkc/backups'
def backup_project(source_path, destination_path):
"""
将项目按日期压缩,存放到其他目录
:param source_path: 源文件夹路径
:param destination_path: 目标文件夹路径
"""
# 创建目标目录(如果它不存在)
if not os.path.exists(source_dir):
raise FileNotFoundError("源文件夹不存在")
if not os.path.exists(destination_dir):
os.makedirs(destination_dir,exist_ok=True)
try:
# 获取时间戳
date_flag = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
# 创建压缩文件路径
archive_path = os.path.join(destination_dir, f"project_backup_{date_flag}")
# 执行备份压缩
backup_path = shutil.make_archive(
archive_path,
"zip",
root_dir=source_dir
)
file_size = os.path.getsize(backup_path) / 1024
print(f'备份完成:备份文件已创建于 {backup_path},大小为 {file_size:.2f} KB')
except Exception as e:
raise Exception(f"备份失败: {str(e)}")
if __name__ == '__main__':
backup_project(PROJECT_DIR, BACKUP_ROOT)
3.2、脚本二:自动备份目录脚本(2)
将源目录先被分到目标目录,再将目标目录打压缩包后存放到目标路径
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: shutil_backup.py
# Description: 先检查磁盘再备份,并且删除已过期的备份文件
# Author: ZKC
# Date: 2026/09/16
#-------------------------------------------------------------------------------
import shutil
import os
import glob
import time
from datetime import datetime
PROJECT_DIR = '/home/zkc/workspace/my_app'
BACKUP_ROOT = '/home/zkc/backups'
def project_backup(source_dir, destination_dir):
"""
将项目按日期备份,存放到其他目录,再进行打包
:param source_dir: 源文件夹路径
:param destination_dir: 目标文件夹路径
"""
# 判断源文件夹是否存在
if not os.path.exists(source_dir) or not os.path.isdir(source_dir):
raise FileNotFoundError(f"源文件夹不存在或者{source_dir}不是一个目录")
archive_path = None
try:
# 检查磁盘空间
total_disk = shutil.disk_usage(destination_dir).total / (1024 ** 3) # 总磁盘空间
used_disk = shutil.disk_usage(destination_dir).used / (1024 ** 3) # 已使用磁盘空间
free_disk = shutil.disk_usage(destination_dir).free / (1024 ** 3) # 可用磁盘空间
# total_disk, used_disk, free_disk = (x / (1024 ** 3) for x in shutil.disk_usage(destination_dir))
use_disk_percent = used_disk / total_disk # 已使用磁盘空间占比
if free_disk < total_disk * 0.1: # 如果可用磁盘空间小于总磁盘空间的10%,则抛出异常
raise OSError(f"磁盘空间不足,无法完成备份。剩余{free_disk:.2f}GB")
if 0.9 < use_disk_percent < 0.95: # 如果磁盘使用率大于90%,则发出警告
print(f"警告:磁盘空间使用率过高, 当前使用率:{use_disk_percent:.1%}")
# 获取时间戳
date_flag = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
# 定义忽略文件的函数
def ignore_files(src_dir, filenames):
ignore_list = []
for file in filenames:
if file.endswith('.tmp') or file.endswith('.log') or file in ['node_modules', '.git']:
ignore_list.append(file)
return ignore_list
# 创建压缩文件路径
archive_path = os.path.join(destination_dir, f"project_backup_{date_flag}")
# 将 源文件 复制 到 目标路径下,复制到 /home/zkc/backups/project_backup_{date_flag} 下
# 如果 目标路径 选 destination_dir,则每次备份的内容没法区分
shutil.copytree(
source_dir,
archive_path,
ignore=ignore_files,
# ignore=lambda root, names: [n for n in names if n == ".git" or n.endswith(".log")],
copy_function=shutil.copy2,
dirs_exist_ok=True
)
# 执行备份文件打包,打包的目标文件是备份的文件目录
backup_path = shutil.make_archive(
archive_path,
"zip",
root_dir=archive_path
)
file_size = os.path.getsize(backup_path) / 1024
print(f'备份完成:备份文件已创建于 {backup_path},大小为 {file_size:.2f} KB')
except Exception:
# 如果 make_archive 抛异常(比如磁盘满了),解压出来的目录不会被自动清理
# 回滚:删除已创建的临时目录,避免留下孤儿目录
if archive_path and os.path.exists(archive_path):
shutil.rmtree(archive_path)
raise
def cleanup_by_age(backup_dir, max_age_days=7):
"""
删除超过 max_age_days 天的备份文件。
:param backup_dir: 备份目录路径
:param max_age_days: 最大保留天数
"""
pattern = os.path.join(backup_dir, "project_backup_*")
backups = glob.glob(pattern)
current_time = time.time()
max_age_seconds = max_age_days * 24 * 60 * 60
for backup_path in backups:
# 获取文件修改时间
mtime = os.path.getmtime(backup_path)
age_seconds = current_time - mtime
if age_seconds > max_age_seconds:
if os.path.isdir(backup_path):
print(f"删除旧文件夹 ({age_seconds / 86400:.1f} 天前): {backup_path}")
shutil.rmtree(backup_path)
else:
print(f"删除旧文件 ({age_seconds / 86400:.1f} 天前): {backup_path}")
os.remove(backup_path)
else:
print(f"保留: {backup_path}")
def cleanup_by_count(backup_dir, keep_count=5):
"""
保留指定数量的备份文件和备份数
"""
prefix = "project_backup_"
# 清理旧版本备份文件和压缩包
# 1、删除旧的备份目录
# os.path.getmtime() 在 Windows 上依赖文件系统的时间戳精度。如果备份操作很快(几秒内连续创建),多个文件的 mtime 可能完全相同
# 直接从文件名解析时间,不依赖 mtime,key是截取每个名字中的时间部分
old_backups_dirs = sorted([bak_dir for bak_dir in os.listdir(backup_dir) if bak_dir.startswith(prefix)
and os.path.isdir(os.path.join(backup_dir, bak_dir))],
key=lambda d: datetime.strptime(d[len(prefix):], "%Y-%m-%d-%H-%M-%S"), reverse=True)
# 2、删除旧的压缩包
# 过滤出.zip结尾的压缩包,通过mtime进行倒序排序
old_backups_archive = sorted([f for f in os.listdir(backup_dir) if f.startswith(prefix)
and f.endswith(".zip")],
key=lambda f: os.path.getmtime(os.path.join(backup_dir, f)), reverse=True)
# 只保留最新的5个备份
for i, dir_name in enumerate(old_backups_dirs):
full_dir_path = os.path.join(backup_dir, dir_name)
if i >= keep_count:
if os.path.isdir(full_dir_path):
print(f"删除文件夹: {dir_name}")
shutil.rmtree(full_dir_path)
else:
raise Exception(f"要删除的该备份文件不是文件夹: {full_dir_path}")
else:
print(f"保留: {dir_name}")
for i, backup_file in enumerate(old_backups_archive):
full_archive_path = os.path.join(backup_dir, backup_file)
if i >= keep_count:
if os.path.isfile(full_archive_path):
print(f"删除文件: {backup_file}")
os.remove(full_archive_path)
else:
raise Exception(f"要删除的该备份文件不是文件: {full_archive_path}")
else:
print(f"保留: {backup_file}")
def backup_and_cleanup(source_dir, destination_dir, max_age_days=7, keep_count=5):
"""执行备份,然后按数量清理旧备份"""
project_backup(source_dir, destination_dir)
print("\n清理旧备份文件:")
print("-" * 40)
# 保留最新的3个备份
cleanup_by_count(destination_dir, keep_count)
if __name__ == '__main__':
backup_and_cleanup(PROJECT_DIR, BACKUP_ROOT, keep_count=3)
3.3、脚本三:批量整理乱序文件
按扩展名分类文件
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: shutil_sort_by_extension.py
# Description: 按扩展名分类文件
# Author: ZKC
# Date: 2026/09/18
#-------------------------------------------------------------------------------
import shutil
import os
from pathlib import Path
PROJECT_DIR = Path('/home/user/workspace/my_app')
BACKUP_ROOT = Path('/home/user/backups')
def sort_by_extension(source_dir, destination_dir):
"""
将目录下的文件 按扩展名 进行分类
:param source_dir: 源文件夹路径
:param destination_dir: 目标文件夹路径
"""
# 判断源文件夹是否存在
if not os.path.exists(source_dir) or not os.path.isdir(source_dir):
raise FileNotFoundError(f"源文件夹不存在或者{source_dir}不是一个目录")
# 遍历源文件夹中的所有文件和子文件夹
for file_path in source_dir.iterdir():
if not file_path.is_file():
continue
# 获取文件的扩展名
extension = file_path.suffix.lstrip(".").lower() or "no_extension"
# 拼接 以扩展名为名称 的目标文件夹路径 如:/home/app/txt
target_dir = destination_dir / extension
# 创建 以扩展名为名称 的目标文件夹, 如果文件夹已存在则忽略
target_dir.mkdir(parents=True, exist_ok=True)
# 拼接 以扩展名为名称 的目标文件路径 如:/home/app/txt/a.txt
target_path = target_dir / file_path.name
# 如果目标文件已存在,则重命名目标文件
if target_path.exists():
counter = 1
while True:
# 重命名目标文件, 避免覆盖已存在的文件, 如:a.txt -> a_1.txt
# file_path.stem = a / file_path.name = a.txt
target_path = target_dir / f"{file_path.stem}_{counter}{file_path.suffix}"
# 如果目标文件不存在,则跳出循环
if not target_path.exists():
break
counter += 1
shutil.move(str(file_path), str(target_path))
print(f'{file_path.name} -> {target_path.relative_to(destination_dir)}')
if __name__ == '__main__':
sort_by_extension(PROJECT_DIR, BACKUP_ROOT)
3.3、脚本四、磁盘空间预警
import shutil
import sys
def check_disk_before_copy(target_dir, needed_size):
usage = shutil.disk_usage(target_dir)
free_gb = usage.free / (1024 ** 3)
needed_gb = needed_size / (1024 ** 3)
if usage.free < needed_size:
print(f'错误: 磁盘空间不足,剩余 {free_gb:.2f} GB,需要 {needed_gb:.2f} GB')
sys.exit(1)
print(f'磁盘空间充足,剩余 {free_gb:.2f} GB')
四、常见报错与实坑排查手册
4.1、文件已存在到底报不报错
shutil 各函数在 “目标已存在” 时的行为不一致,这是最容易踩坑的地方。整理成表格方便查看:
| 函数 | 目标已存在时的行为 |
|---|---|
| copyfile / copy / copy2 | 直接覆盖,不报错 |
| copyfileobj | 取决于打开文件对象时的模式, wb 会覆盖 |
| move | 目标为文件时覆盖;目标为目录时移入目录 |
| copytree | 抛 FileExistsError |
| rmtree | 目录不存在时抛 FileNotFoundError |
4.2、权限问题:Windows 和 Linux 的差别
在 Linux 上,如果你对目标目录没有写权限, shutil.copy 会抛出 PermissionError 。在 Windows 上,如果你尝试复制一个正在被其他程序打开的文件,也会遇到权限错误。我在 Windows 上遇到过更特殊的情况:目标文件被设置成了只读属性, shutil.copy 会失败,因为无法覆盖只读文件。后来我先用 os.chmod 去掉只读属性,再执行复制。
import os
import shutil
def force_copy(src, dst):
if os.path.exists(dst):
# 去除只读属性
os.chmod(dst, 0o666)
shutil.copy2(src, dst)
4.3、跨设备移动的性能陷阱
shutil.move 的底层虽然会自动处理跨设备,但我要提醒大家:这个自动处理是有代价的。当源和目标在同一文件系统时, move 走的是 os.rename ,几乎是瞬间完成。但当跨文件系统时,它会先完整复制数据,再删除源文件,对大文件来说耗时和临时磁盘占用都不可忽视。
如果你在写一个需要频繁移动大文件的脚本,建议先判断源和目标是否在同一文件系统上,再决定用 os.rename 还是 shutil.move ,能省一部分不必要的复制时间。不过在绝大多数应用场景下,直接用 shutil.move 更省心,毕竟跨设备自动降级处理不是所有模块都能做到的。
五、结尾经验:
我的经验是:文件操作越简单越不容易出错,所以写这类代码时不要贪图省事跳过异常处理。一个看似没必要的 try-except ,可能在你部署到新环境的时候救你一命。
282



被折叠的 条评论
为什么被折叠?



