Python脚本遍历Excel文件:按唯一字符串重命名或归类
解决方案与代码优化建议
一、批量遍历文件夹内的Excel文件
用glob可以简洁遍历目标文件夹下所有.xlsx文件,支持递归扫描子文件夹:
import glob import os # 遍历指定文件夹下的xlsx文件 excel_files = glob.glob(r"目标文件夹路径\*.xlsx") # 若要包含子文件夹,添加recursive=True excel_files = glob.glob(r"目标文件夹路径\**\*.xlsx", recursive=True)
二、提取唯一标识(基于Report单元格偏移)
将查找逻辑封装为函数,找到Report单元格后,根据偏移量提取唯一标识——这是重命名/分类的核心依据:
import openpyxl def get_unique_id(file_path, shift_col=5, shift_row=5): try: # 只读模式加载,提升大文件处理速度 wb = openpyxl.load_workbook(file_path, read_only=True) found = False for sheet_name in wb.sheetnames: if found: break ws = wb[sheet_name] # 替代已弃用的get_sheet_by_name方法 # 遍历前50行50列,可根据实际数据范围调整 for row in range(1, 51): if found: break for col in range(1, 51): cell_value = ws.cell(row=row, column=col).value if cell_value == 'Report': # 定位偏移后的目标单元格 target_cell = ws.cell(row=row + shift_row, column=col + shift_col) unique_id = target_cell.value if unique_id: found = True return str(unique_id).strip() else: print(f"文件{file_path}中Report偏移单元格为空") return None print(f"文件{file_path}未找到Report字符串") return None except Exception as e: print(f"处理文件{file_path}出错: {str(e)}") return None
三、重命名或移动文件
1. 重命名文件
提取唯一标识后修改文件名,自动处理重复标识的冲突:
import os def rename_file(file_path, unique_id): dir_name = os.path.dirname(file_path) ext = os.path.splitext(file_path)[1] new_name = f"{unique_id}{ext}" new_path = os.path.join(dir_name, new_name) # 文件名重复时添加序号后缀 counter = 1 while os.path.exists(new_path): new_name = f"{unique_id}_{counter}{ext}" new_path = os.path.join(dir_name, new_name) counter += 1 os.rename(file_path, new_path) print(f"已重命名: {file_path} -> {new_path}")
2. 移动文件到对应分类文件夹
根据唯一标识创建专属文件夹,再移动文件,同样处理重复文件:
import shutil def move_to_folder(file_path, unique_id, target_root="分类文件夹"): target_folder = os.path.join(target_root, unique_id) # 文件夹不存在则自动创建 os.makedirs(target_folder, exist_ok=True) file_name = os.path.basename(file_path) new_path = os.path.join(target_folder, file_name) # 文件重复时添加序号后缀 counter = 1 name, ext = os.path.splitext(file_name) while os.path.exists(new_path): new_name = f"{name}_{counter}{ext}" new_path = os.path.join(target_folder, new_name) counter += 1 shutil.move(file_path, new_path) print(f"已移动: {file_path} -> {new_path}")
四、整合完整批量处理脚本
将上述模块整合,一键完成批量遍历、标识提取、文件操作:
import glob import os import openpyxl import shutil def get_unique_id(file_path, shift_col=5, shift_row=5): try: wb = openpyxl.load_workbook(file_path, read_only=True) found = False for sheet_name in wb.sheetnames: if found: break ws = wb[sheet_name] for row in range(1, 51): if found: break for col in range(1, 51): cell_value = ws.cell(row=row, column=col).value if cell_value == 'Report': target_cell = ws.cell(row=row + shift_row, column=col + shift_col) unique_id = target_cell.value if unique_id: found = True return str(unique_id).strip() else: print(f"文件{file_path}中Report偏移单元格为空") return None print(f"文件{file_path}未找到Report字符串") return None except Exception as e: print(f"处理文件{file_path}出错: {str(e)}") return None def rename_file(file_path, unique_id): dir_name = os.path.dirname(file_path) ext = os.path.splitext(file_path)[1] new_name = f"{unique_id}{ext}" new_path = os.path.join(dir_name, new_name) counter = 1 while os.path.exists(new_path): new_name = f"{unique_id}_{counter}{ext}" new_path = os.path.join(dir_name, new_name) counter += 1 os.rename(file_path, new_path) print(f"已重命名: {file_path} -> {new_path}") def move_to_folder(file_path, unique_id, target_root="分类文件夹"): target_folder = os.path.join(target_root, unique_id) os.makedirs(target_folder, exist_ok=True) file_name = os.path.basename(file_path) new_path = os.path.join(target_folder, file_name) counter = 1 name, ext = os.path.splitext(file_name) while os.path.exists(new_path): new_name = f"{name}_{counter}{ext}" new_path = os.path.join(target_folder, new_name) counter += 1 shutil.move(file_path, new_path) print(f"已移动: {file_path} -> {new_path}") if __name__ == "__main__": # 替换为你的Excel文件所在文件夹路径 target_dir = r"你的目标文件夹路径" excel_files = glob.glob(os.path.join(target_dir, "*.xlsx"), recursive=True) # 选择执行重命名或移动操作,注释掉不需要的部分 for file in excel_files: unique_id = get_unique_id(file) if unique_id: # 重命名文件 rename_file(file, unique_id) # 或移动到分类文件夹 # move_to_folder(file, unique_id)
额外注意事项
- 先备份原始文件:批量操作前务必复制一份原始数据,避免操作失误导致文件丢失。
- 调整遍历范围:如果你的Excel数据超出前50行50列,修改
range(1,51)为对应数值。 - 兼容
.xls文件:若存在老版本Excel文件,需改用xlrd库(注意xlrd 2.0+仅支持.xls格式)。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

