Python 的 Shutil 模块,你都了解多少?("Python Shutil 模块详解:你真的了解它的所有功能吗?")

原创
ithorizon 6个月前 (10-20) 阅读数 21 #后端开发

Python Shutil 模块详解:你真的了解它的所有功能吗?

一、Shutil 模块简介

Python 的 shutil 模块是一个用于文件和文件集合的高级操作工具。它提供了许多用于文件操作的方法,如复制、移动、删除等。shutil 模块是 Python 标准库的一部分,故而无需安装任何额外的包即可使用。

二、Shutil 常用方法

以下是 shutil 模块中一些常用的方法及其功能:

1. shutil.copy(src, dst)

复制文件。将 src 指定的文件复制到 dst 指定的位置。

def copy_file(src, dst):

shutil.copy(src, dst)

print(f"文件已复制:{src} -> {dst}")

2. shutil.copy2(src, dst)

类似于 shutil.copy(),但会尝试保留文件的元数据(如修改时间等)。

def copy_file_with_metadata(src, dst):

shutil.copy2(src, dst)

print(f"文件已复制并保留元数据:{src} -> {dst}")

3. shutil.move(src, dst)

移动文件或目录。将 src 指定的文件或目录移动到 dst 指定的位置。

def move_file(src, dst):

shutil.move(src, dst)

print(f"文件已移动:{src} -> {dst}")

4. shutil.rmtree(path)

删除目录及其所有内容。这是一个递归操作,会删除目录下的所有文件和子目录。

def remove_directory(path):

shutil.rmtree(path)

print(f"目录已删除:{path}")

5. shutil.copytree(src, dst, symlinks=False)

递归复制目录。将 src 指定的目录复制到 dst 指定的位置。

def copy_directory(src, dst):

shutil.copytree(src, dst)

print(f"目录已复制:{src} -> {dst}")

6. shutil.make_archive(base_name, format, root_dir=None, base_dir=None)

创建压缩文件。base_name 是压缩文件的基本名称,format 是压缩格式(如 'zip'、'tar' 等),root_dir 是要压缩的目录,base_dir 是压缩文件中的根目录。

def create_archive(base_name, format, root_dir):

shutil.make_archive(base_name, format, root_dir)

print(f"压缩文件已创建:{base_name}.{format}")

三、进阶功能

除了上述常用方法,shutil 模块还提供了以下一些进阶功能:

1. shutil.ignore_patterns(*patterns)

在复制或移动文件时,可以指定忽略某些文件的模式。patterns 是一个包含模式字符串的元组。

import os

def copy_directory_ignore_patterns(src, dst, ignore_patterns):

ignore = shutil.ignore_patterns(*ignore_patterns)

shutil.copytree(src, dst, ignore=ignore)

print(f"目录已复制,忽略模式:{ignore_patterns},源目录:{src} -> 目标目录:{dst}")

2. shutil.get_terminal_size(fallback=(80, 24))

获取终端的尺寸。fallback 是当无法确定终端尺寸时使用的默认值。

def get_terminal_size():

size = shutil.get_terminal_size()

print(f"终端尺寸:宽度={size.columns}, 高度={size.lines}")

四、Shutil 模块在实践中的应用

以下是 shutil 模块在实际开发中的一些应用场景:

1. 备份文件

在处理重要文件时,我们通常需要创建备份。使用 shutil 模块,可以轻松实现文件的备份。

def backup_file(src, backup_dir):

if not os.path.exists(backup_dir):

os.makedirs(backup_dir)

shutil.copy2(src, os.path.join(backup_dir, os.path.basename(src)))

print(f"文件备份顺利:{src} -> {backup_dir}")

2. 同步目录

在多个设备之间同步文件时,可以使用 shutil 模块来比较和同步目录内容。

def sync_directories(src, dst):

for item in os.listdir(src):

s = os.path.join(src, item)

d = os.path.join(dst, item)

if os.path.isdir(s):

if not os.path.exists(d):

os.makedirs(d)

sync_directories(s, d)

else:

if not os.path.exists(d) or os.path.getmtime(d) < os.path.getmtime(s):

shutil.copy2(s, d)

print(f"目录已同步:{src} -> {dst}")

3. 清理临时文件

在程序运行过程中,也许会产生一些临时文件。使用 shutil 模块,可以方便地清理这些临时文件。

def cleanup_temp_files(temp_dir):

for item in os.listdir(temp_dir):

item_path = os.path.join(temp_dir, item)

if os.path.isfile(item_path):

os.remove(item_path)

elif os.path.isdir(item_path):

shutil.rmtree(item_path)

print(f"临时文件已清理:{temp_dir}")

五、总结

shutil 模块是 Python 标准库中一个非常有用的模块,提供了丰盈的文件操作方法。通过本文的介绍,相信您已经对 shutil 模块有了更深入的了解。在实际开发中,灵活运用 shutil 模块,可以大大尽也许缩减损耗工作高效。


本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: 后端开发


热门