Python批量文件案例如何批量操作

wen python案例 20

本文目录导读:

Python批量文件案例如何批量操作

  1. 完整案例:批量处理txt文件
  2. 更多实用案例
  3. 批量操作技巧总结

我来用一个完整的案例演示Python批量文件操作,这个案例包含常见场景:批量重命名、批量复制、批量删除、批量修改内容。

完整案例:批量处理txt文件

import os
import shutil
import glob
from pathlib import Path
class FileBatchProcessor:
    """文件批量处理器"""
    def __init__(self, workspace_dir="batch_files"):
        self.workspace_dir = Path(workspace_dir)
        self.create_workspace()
    def create_workspace(self):
        """创建工作目录和示例文件"""
        self.workspace_dir.mkdir(exist_ok=True)
        # 创建多个示例txt文件
        for i in range(1, 11):  # 创建10个文件
            file_path = self.workspace_dir / f"document_{i:03d}.txt"
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(f"这是第{i}个文档\n日期:2024-01-{i:02d}\n内容示例\n")
        print(f"已创建10个示例文件在 {self.workspace_dir}")
    def batch_rename(self, pattern="*", prefix="new_", keep_original=False):
        """批量重命名文件
        Args:
            pattern: 文件匹配模式
            prefix: 新文件名前缀
            keep_original: 是否保留原文件
        """
        print(f"\n=== 批量重命名(前缀: {prefix})===")
        for file_path in self.workspace_dir.glob(pattern):
            if file_path.is_file():
                new_name = f"{prefix}{file_path.name}"
                new_path = file_path.with_name(new_name)
                if keep_original:
                    shutil.copy2(file_path, new_path)
                    print(f"复制并重命名: {file_path.name} -> {new_name}")
                else:
                    file_path.rename(new_path)
                    print(f"重命名: {file_path.name} -> {new_name}")
    def batch_copy(self, pattern="*.txt", dest_dir="backup"):
        """批量复制文件到指定目录"""
        dest_path = self.workspace_dir / dest_dir
        dest_path.mkdir(exist_ok=True)
        print(f"\n=== 批量复制到 {dest_dir} ===")
        for file_path in self.workspace_dir.glob(pattern):
            shutil.copy2(file_path, dest_path / file_path.name)
            print(f"已复制: {file_path.name}")
        print(f"共复制 {len(list(dest_path.glob('*')))} 个文件")
    def batch_delete(self, pattern="*.bak", confirm=True):
        """批量删除文件"""
        files_to_delete = list(self.workspace_dir.glob(pattern))
        if not files_to_delete:
            print(f"没有找到匹配 {pattern} 的文件")
            return
        print(f"\n=== 批量删除(模式: {pattern})===")
        print(f"找到 {len(files_to_delete)} 个文件:")
        for f in files_to_delete:
            print(f"  - {f.name}")
        if confirm and input("确认删除? (y/n): ").lower() != 'y':
            print("取消删除")
            return
        for file_path in files_to_delete:
            file_path.unlink()
            print(f"已删除: {file_path.name}")
    def batch_modify_content(self, pattern="*.txt", old_text=None, new_text=None):
        """批量修改文件内容"""
        if old_text is None and new_text is None:
            # 添加行号
            print(f"\n=== 批量添加行号 ===")
            for file_path in self.workspace_dir.glob(pattern):
                with open(file_path, 'r', encoding='utf-8') as f:
                    lines = f.readlines()
                # 添加行号
                new_lines = []
                for i, line in enumerate(lines, 1):
                    new_lines.append(f"{i:03d}: {line}")
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.writelines(new_lines)
                print(f"已处理: {file_path.name}")
        else:
            # 替换文本
            print(f"\n=== 批量替换文本: '{old_text}' -> '{new_text}' ===")
            for file_path in self.workspace_dir.glob(pattern):
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                new_content = content.replace(old_text, new_text)
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(new_content)
                print(f"已修改: {file_path.name}")
    def list_files(self, pattern="*"):
        """列出工作目录下的文件"""
        print(f"\n=== 文件列表 ===")
        for file_path in sorted(self.workspace_dir.glob(pattern)):
            if file_path.is_file():
                size = file_path.stat().st_size
                print(f"{file_path.name:20s} {size:>6d} 字节")
        print(f"共 {len(list(self.workspace_dir.glob(pattern)))} 个文件")
# 使用示例
if __name__ == "__main__":
    processor = FileBatchProcessor("my_test_files")
    # 1. 查看初始状态
    processor.list_files()
    # 2. 批量重命名(添加前缀)
    processor.batch_rename(pattern="*.txt", prefix="processed_")
    processor.list_files()
    # 3. 批量复制到备份目录
    processor.batch_copy(dest_dir="backup_2024")
    # 4. 批量修改内容(添加行号)
    processor.batch_modify_content(old_text="这是第", new_text="文档编号:")
    # 5. 查看最终文件
    processor.list_files()
    # 6. 清理示例
    # processor.batch_delete(pattern="*.txt")

更多实用案例

案例1:批量处理图片(压缩/调整大小)

from PIL import Image
from pathlib import Path
def batch_resize_images(source_dir, target_dir, size=(800, 600)):
    """批量调整图片大小"""
    source_path = Path(source_dir)
    target_path = Path(target_dir)
    target_path.mkdir(exist_ok=True)
    for img_path in source_path.glob("*.jpg"):
        with Image.open(img_path) as img:
            # 保持比例调整大小
            img.thumbnail(size, Image.Resampling.LANCZOS)
            target_file = target_path / img_path.name
            img.save(target_file, "JPEG", quality=85)
            print(f"已处理: {img_path.name}")

案例2:批量处理Excel文件

import pandas as pd
from pathlib import Path
def batch_merge_excel(pattern="*.xlsx"):
    """批量合并Excel文件"""
    all_data = []
    for file_path in Path().glob(pattern):
        df = pd.read_excel(file_path)
        df['来源文件'] = file_path.name
        all_data.append(df)
        print(f"读取: {file_path.name}")
    if all_data:
        result = pd.concat(all_data, ignore_index=True)
        result.to_excel("合并结果.xlsx", index=False)
        print(f"合并完成,共 {len(result)} 行数据")

批量操作技巧总结

使用pathlib替代os.path

# 推荐使用
from pathlib import Path
p = Path("path/to/file.txt")
p.exists()  # 检查是否存在
p.is_file()  # 是否是文件
p.rename("new_name.txt")  # 重命名
p.unlink()  # 删除

安全操作模式

def safe_batch_operation():
    """安全的批量操作"""
    import traceback
    success_count = 0
    error_count = 0
    for file_path in Path().glob("*.txt"):
        try:
            # 执行操作
            success_count += 1
        except Exception as e:
            error_count += 1
            print(f"处理 {file_path.name} 时出错: {e}")
            traceback.print_exc()
    print(f"成功: {success_count}, 失败: {error_count}")

进度显示

def batch_with_progress(pattern="*"):
    """带进度显示的批量操作"""
    files = list(Path().glob(pattern))
    total = len(files)
    for i, file_path in enumerate(files, 1):
        progress = i / total * 100
        print(f"\r进度: {progress:.1f}% ({i}/{total})", end="")
        # 执行批量操作
    print("\n完成!")

配置文件驱动

import json
def batch_from_config(config_file):
    """从配置文件读取批量操作"""
    with open(config_file, 'r') as f:
        config = json.load(f)
    operation = config.get("operation")
    pattern = config.get("pattern")
    options = config.get("options", {})
    if operation == "rename":
        batch_rename(pattern, **options)
    elif operation == "copy":
        batch_copy(pattern, **options)

这个案例涵盖了大多数常见的批量文件操作场景,关键点是:

  • 使用pathlib提供更现代的API
  • 做好错误处理
  • 添加进度显示
  • 考虑备份和回滚

需要更具体的某个场景的案例吗?

抱歉,评论功能暂时关闭!