基于文件首行内容批量重命名的Python脚本实现


阅读 8 次

场景需求分析

在日常开发中,我们经常需要处理批量文件重命名任务。特别是当需要根据文件内容特征进行重命名时,手动操作效率极低。比如收集的日志文件需要按首行时间戳重命名,或是文档需要按标题重命名。

Python实现方案

使用Python的os模块配合正则表达式可以完美解决这个问题。以下是完整实现代码:


import os
import re

def rename_files_by_first_word(folder_path):
    # 获取文件夹内所有文件
    for filename in os.listdir(folder_path):
        filepath = os.path.join(folder_path, filename)
        
        # 只处理普通文件
        if os.path.isfile(filepath):
            try:
                with open(filepath, 'r', encoding='utf-8') as f:
                    first_line = f.readline().strip()
                    
                # 提取第一个有效单词
                if first_line:
                    # 使用正则匹配第一个单词(中文或英文)
                    match = re.search(r'[\u4e00-\u9fa5a-zA-Z]+', first_line)
                    if match:
                        new_name = match.group(0) + os.path.splitext(filename)[1]
                        new_path = os.path.join(folder_path, new_name)
                        
                        # 避免文件名冲突
                        counter = 1
                        while os.path.exists(new_path):
                            new_name = f"{match.group(0)}_{counter}{os.path.splitext(filename)[1]}"
                            new_path = os.path.join(folder_path, new_name)
                            counter += 1
                            
                        os.rename(filepath, new_path)
                        print(f"重命名成功: {filename} -> {new_name}")
            except Exception as e:
                print(f"处理文件 {filename} 时出错: {str(e)}")

# 使用示例
rename_files_by_first_word('./documents')

代码优化建议

1. 增加文件编码自动检测功能,避免中文乱码问题


import chardet

def detect_encoding(filepath):
    with open(filepath, 'rb') as f:
        rawdata = f.read(1024)
    return chardet.detect(rawdata)['encoding']

2. 增加多线程处理提升大批量文件处理速度


from concurrent.futures import ThreadPoolExecutor

def batch_rename(folder_path, workers=4):
    with ThreadPoolExecutor(max_workers=workers) as executor:
        for filename in os.listdir(folder_path):
            filepath = os.path.join(folder_path, filename)
            executor.submit(process_file, filepath)

常见问题处理

文件名冲突:代码中已实现自动添加序号解决冲突

特殊字符:Windows系统文件名不能包含 \ / : * ? " < > | 等字符,需要过滤


import string

valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
new_name = ''.join(c for c in new_name if c in valid_chars)

扩展应用场景

1. 按文件内容特征分类:可以修改代码实现按特定规则将文件分类到不同子目录

2. 结合PDF/Word解析:使用PyPDF2或python-docx库处理非纯文本文件

3. 集成到自动化流程:作为CI/CD流水线的一部分,自动整理构建产物