文章目录 Python shutil模块详解 一、模块基础 二、文件操作 三、目录操作 四、归档操作 五、磁盘空间管理 六、高级功能 七、异常处理 八、最佳实践 九、与os模块对比 十、总结
Python shutil模块详解
shutil(shell utility的缩写)是Python标准库中用于高级文件操作 的核心模块,提供了比os模块更便捷的文件和目录管理功能。下面我将全面讲解shutil模块的各类功能。
一、模块基础
1. 模块导入
import shutil
2. 模块特点
提供高级文件操作接口 支持递归目录操作 包含归档/压缩功能 跨平台兼容
二、文件操作
1. 文件操作方法对比
方法 描述 是否保留元数据 示例 shutil.copy()
复制文件内容 不保留 shutil.copy("src.txt", "dst.txt")
shutil.copy2()
复制文件内容和元数据 保留 shutil.copy2("src.txt", "dst.txt")
shutil.copyfile()
仅复制内容(更低级) 不保留 shutil.copyfile("src.txt", "dst.txt")
shutil.copyfileobj()
复制文件对象 - shutil.copyfileobj(src_fp, dst_fp)
shutil.move()
移动/重命名文件 保留 shutil.move("old.txt", "new.txt")
2. 代码示例
shutil. copy( "source.txt" , "backup.txt" )
shutil. copy2( "config.ini" , "config_backup.ini" )
shutil. move( "old_name.txt" , "new_name.txt" )
with open ( "src.bin" , "rb" ) as src, open ( "dst.bin" , "wb" ) as dst: shutil. copyfileobj( src, dst, length= 16 * 1024 )
三、目录操作
1. 目录操作方法对比
方法 描述 是否递归 示例 shutil.copytree()
复制整个目录树 是 shutil.copytree("src", "dst")
shutil.rmtree()
删除整个目录树 是 shutil.rmtree("dir")
shutil.move()
移动/重命名目录 - shutil.move("old_dir", "new_dir")
2. 代码示例
shutil. copytree( "source_dir" , "backup_dir" , ignore= shutil. ignore_patterns( "*.tmp" , "temp*" ) )
shutil. rmtree( "obsolete_dir" , ignore_errors= True )
shutil. move( "old_project" , "new_project" )
def ignore_pycache ( dirname, filenames) : return [ name for name in filenames if name == "__pycache__" ] shutil. copytree( "src" , "dst" , ignore= ignore_pycache)
四、归档操作
1. 归档格式支持
格式 方法 示例 ZIP make_archive()
/unpack_archive()
shutil.make_archive("backup", "zip", "src")
TAR make_archive()
/unpack_archive()
shutil.make_archive("backup", "tar", "src")
GZTAR make_archive()
shutil.make_archive("backup", "gztar", "src")
BZTAR make_archive()
shutil.make_archive("backup", "bztar", "src")
XZTAR make_archive()
shutil.make_archive("backup", "xztar", "src")
2. 归档操作代码
shutil. make_archive( "data_backup" , "zip" , "data" )
import time
archive_name = f"backup_ { time. strftime( '%Y%m%d' ) } "
shutil. make_archive( archive_name, "gztar" , "project" )
shutil. unpack_archive( "backup.zip" , "restore_dir" )
print ( shutil. get_archive_formats( ) )
五、磁盘空间管理
1. 磁盘空间方法
方法 描述 示例 shutil.disk_usage()
获取磁盘使用情况 usage = shutil.disk_usage("/")
shutil.which()
查找可执行程序路径 python_path = shutil.which("python")
2. 代码示例
usage = shutil. disk_usage( "/" )
print ( f"总空间: { usage. total/ 1024 / 1024 : .1f } MB" )
print ( f"已用空间: { usage. used/ 1024 / 1024 : .1f } MB" )
print ( f"剩余空间: { usage. free/ 1024 / 1024 : .1f } MB" )
python_path = shutil. which( "python3" )
print ( f"Python路径: { python_path} " )
六、高级功能
1. 自定义复制行为
def custom_copy ( src, dst, * , follow_symlinks= True ) : print ( f"正在复制 { src} 到 { dst} " ) return shutil. copy2( src, dst, follow_symlinks= follow_symlinks)
shutil. copy = custom_copy
shutil. copy( "a.txt" , "b.txt" )
2. 处理特殊文件
def special_file_handler ( src, dst, * , follow_symlinks= True ) : if os. path. isdir( src) : raise ValueError( "不支持目录" ) with open ( src, 'rb' ) as fsrc, open ( dst, 'wb' ) as fdst: shutil. copyfileobj( fsrc, fdst) return dstshutil. register_unpack_format( 'special' , [ '.spl' ] , special_file_handler)
七、异常处理
1. 常见异常类型
异常 描述 触发场景 shutil.Error
多文件操作错误 copytree/rmtree中出现多个错误 shutil.SameFileError
源和目标相同 copy/copy2(src, src) shutil.ExecError
执行错误 归档/解压失败 OSError
系统级错误 权限不足/磁盘满等
2. 异常处理示例
try : shutil. copytree( "src" , "dst" )
except shutil. Error as e: print ( f"复制错误: { e} " ) for src, dst, err_msg in e. args[ 0 ] : print ( f"失败: { src} -> { dst} : { err_msg} " )
except OSError as e: print ( f"系统错误: { e} " )
八、最佳实践
优先使用copy2 :保留文件元数据处理大文件使用copyfileobj :可控制缓冲区大小copytree前检查目标 :避免意外覆盖使用ignore参数过滤文件 :提高效率处理磁盘空间 :大文件操作前检查考虑错误恢复 :捕获并处理异常临时文件使用tempfile :更安全可靠
九、与os模块对比
功能 os模块 shutil模块 文件复制 需手动读写 copy()/copy2()
目录复制 需递归实现 copytree()
目录删除 只能删空目录 rmtree()
可删非空目录文件移动 os.rename()
有限制move()
更强大归档操作 无 make_archive()
十、总结
shutil模块提供了:
高级文件/目录操作接口 递归目录处理能力 多种归档格式支持 磁盘空间管理工具 丰富的异常处理机制
它是Python文件系统编程中不可或缺的工具,特别适合需要复杂文件操作的场景。合理使用shutil可以大幅简化代码并提高可靠性。