Python 的 shutil 模块是一个强大的工具,用于执行各种文件和目录操作,如复制、移动、删除等。本文将深入探讨 shutil 模块的各种功能和方法,并提供丰富的示例代码,帮助大家更好地理解和运用这个工具。
shutil.copy() 函数用于复制单个文件,shutil.copytree() 函数用于复制整个目录树。
示例:
- import shutil
-
- # 复制单个文件
- shutil.copy("source.txt", "destination.txt")
-
- # 复制整个目录树
- shutil.copytree("source_dir", "destination_dir")
shutil.move() 函数用于移动文件或目录,类似于命令行中的 mv 命令。
示例:
- import shutil
-
- # 移动单个文件
- shutil.move("source.txt", "destination.txt")
-
- # 移动整个目录树
- shutil.move("source_dir", "destination_dir")
shutil.rmtree() 函数用于递归删除整个目录树,os.remove() 函数用于删除单个文件。
示例:
- import shutil
-
- # 删除整个目录树
- shutil.rmtree("directory_to_delete")
-
- # 删除单个文件
- os.remove("file_to_delete.txt")
shutil 模块还提供了许多其他功能,如创建压缩文件、解压缩文件等。
示例:
- import shutil
-
- # 创建压缩文件
- shutil.make_archive("archive", "zip", "source_dir")
-
- # 解压缩文件
- shutil.unpack_archive("archive.zip", "destination_dir")
在进行文件和目录操作时,可能会遇到各种异常情况,如文件不存在、权限不足等。shutil 模块提供了相应的异常处理机制,以保证程序的稳定性。
示例:
- import shutil
-
- try:
- # 尝试复制文件
- shutil.copy("nonexistent_file.txt", "destination.txt")
- except FileNotFoundError:
- print("文件不存在")
在进行文件和目录操作时,有时需要对文件或目录进行过滤,只处理符合特定条件的文件或目录。shutil 模块提供了一些函数,可以根据不同的过滤条件来操作文件和目录。
示例:
- import shutil
-
- # 只复制指定后缀名的文件
- def copy_files_with_extension(source_dir, destination_dir, extension):
- for root, dirs, files in os.walk(source_dir):
- for file in files:
- if file.endswith(extension):
- shutil.copy(os.path.join(root, file), destination_dir)
-
- # 复制大小不超过 1MB 的文件
- def copy_small_files(source_dir, destination_dir, max_size):
- for root, dirs, files in os.walk(source_dir):
- for file in files:
- file_path = os.path.join(root, file)
- if os.path.getsize(file_path) <= max_size:
- shutil.copy(file_path, destination_dir)
-
- # 复制最近修改时间在一周内的文件
- def copy_recent_files(source_dir, destination_dir, days):
- cutoff_time = time.time() - days * 24 * 60 * 60
- for root, dirs, files in os.walk(source_dir):
- for file in files:
- file_path = os.path.join(root, file)
- if os.path.getmtime(file_path) >= cutoff_time:
- shutil.copy(file_path, destination_dir)
shutil 模块也提供了一些函数用于修改文件和目录的权限,如更改所有者、更改访问权限等。
示例:
- import shutil
-
- # 修改文件所有者
- def change_owner(file_path, owner):
- shutil.chown(file_path, user=owner)
-
- # 修改文件权限
- def change_permissions(file_path, mode):
- shutil.chmod(file_path, mode)
shutil 模块还提供了一些函数用于处理符号链接文件,如创建符号链接、解析符号链接等。
示例:
- import shutil
-
- # 创建符号链接
- def create_symlink(target, link_name):
- shutil.symlink(target, link_name)
-
- # 解析符号链接
- def resolve_symlink(link_name):
- return os.path.realpath(link_name)
shutil 模块是 Python 中一个功能强大且方便实用的工具,用于执行各种文件和目录操作。通过深入了解和灵活运用 shutil 模块的各种功能和方法,可以更好地处理文件和目录,提高程序的效率和稳定性。在实际应用中,建议根据具体需求,选择合适的 shutil 函数,并结合其他标准库模块和第三方库,以满足实际的文件和目录操作需求。