4.3 python 基础 - 常用的python模块 - shutil、os 和 re

52 阅读2分钟

目录

  1. shutil模块的介绍与用法
  2. os模块的介绍与用法
  3. 正则表达式与re模块的介绍与用法
  4. 实践案例:批量重命名图片文件

1. shutil模块的介绍与用法

shutil是Python标准库的一部分,用于高级文件操作。:

  • 删除文件:使用shutil.rmtree(path)删除整个目录树。
  • 拷贝文件:使用shutil.copy(src, dst)复制单个文件。
  • 拷贝文件夹:使用shutil.copytree(src, dst)复制整个目录树。
  • 重命名:使用os.rename(src, dst)重命名文件或目录。
  • 压缩:使用shutil.make_archive(base_name, format, root_dir, base_dir)创建压缩文件。
  • 解压缩:使用shutil.unpack_archive(filename, extract_dir=None, format=None)解压压缩文件。

示例代码:

  1. 复制单个文件

    import shutil
    
    # 复制单个文件
    shutil.copy('source.txt', 'destination.txt')
    
  2. 复制整个目录

    import shutil
    
    # 复制整个目录
    shutil.copytree('source_dir', 'destination_dir')
    
  3. 移动文件或目录

    import shutil
    
    # 移动文件
    shutil.move('source.txt', 'destination_dir/source.txt')
    
    # 移动目录
    shutil.move('source_dir', 'new_location/source_dir')
    
  4. 删除整个目录

    import shutil
    
    # 删除目录
    shutil.rmtree('directory_to_delete')
    
  5. 创建归档和解压归档

    import shutil
    import os
    
    # 创建归档
    archive_name = 'my_archive.zip'
    root_dir = '.'
    base_dir = 'data_to_archive'
    shutil.make_archive(archive_name, 'zip', root_dir, base_dir)
    
    # 解压归档
    extract_dir = 'extracted_data'
    shutil.unpack_archive(archive_name, 
    

2. os模块的介绍与用法

os模块提供了丰富的方法来处理文件和目录,包括创建、删除、重命名等。

  • 获取当前工作目录os.getcwd()
  • 改变当前工作目录os.chdir(path)
  • 列出目录内容os.listdir(path)
  • 创建目录os.makedirs(path)
  • 删除空目录os.rmdir(path)

示例代码:获取当前工作目录

import os

# 获取当前工作目录
current_directory = os.getcwd()
print(current_directory)

3. 正则表达式与re模块的介绍与用法

正则表达式是一种强大的文本匹配工具,用于搜索、替换符合某个模式的文本。Python的re模块提供了正则表达式的实现。

  • 字符类:如\d匹配数字,\w匹配字母和数字。
  • 数量词:如*表示0次或多次,+表示1次或多次,?表示0次或1次。
  • 分组:使用圆括号()来创建分组。

在Python中,re模块提供了以下常用方法:

  • re.findall(pattern, string):找到字符串中所有匹配的子串。
  • re.match(pattern, string):从字符串的开始位置匹配模式。
  • re.search(pattern, string):在字符串中搜索模式。

示例代码:使用正则表达式匹配数字

import re

text = "There are 123 apples and 456 oranges."
numbers = re.findall(r'\d+', text)
print(numbers)  # 输出:['123', '456']

实践案例:批量重命名图片文件

假设我们需要在某个目录下找到所有以.png为后缀的文件,并将其重命名为.jpeg后缀。

import os
import re

# 要搜索的目录
directory = 'path/to/directory'

# 遍历目录
for filename in os.listdir(directory):
    # 检查文件扩展名
    if re.search(r'\.png$', filename):
        # 构造原始文件路径
        old_file = os.path.join(directory, filename)
        # 构造新文件名
        new_filename = re.sub(r'\.png$', '.jpeg', filename)
        # 构造新文件路径
        new_file = os.path.join(directory, new_filename)
        # 重命名文件
        os.rename(old_file, new_file)
        print(f'Renamed {old_file} to {new_file}')