如何用Python批量重命名文件,匹配不同目录的文件名格式?
批量重命名匹配目录文件名解决方案
问题分析
目录1的MP4文件名(如00HFP.mp4、0AMBV.mp4)经处理后,目录2生成的USD文件名首字符被替换为下划线(如_0HFP.usd对应00HFP.mp4,_AMBV.usd对应0AMBV.mp4),需批量将目录2的USD文件重命名为与目录1MP4文件的主文件名一致。
原代码未成功的可能原因:
- 路径指向错误,导致无法定位目标文件
- 缺少异常处理,无法排查重命名失败的具体问题
- 无日志输出,无法确认哪些文件完成匹配或未找到
修正后的Python脚本
import pathlib # 替换为你的实际目录路径 dir1 = pathlib.Path('./mnt/d/Downloads/Charades_v1_480/charades_18Jan/done/') dir2 = pathlib.Path('./mnt/d/Downloads/Charades_v1_480/charades_18Jan_anim/pt-charades-output/') # 预存目录2的USD文件映射:去掉下划线的主名 -> 文件路径 usd_file_map = {} for usd_file in dir2.glob('*.usd'): stripped_stem = usd_file.stem.lstrip('_') usd_file_map[stripped_stem] = usd_file # 遍历目录1的MP4文件,匹配并重命名对应USD文件 for mp4_file in dir1.glob('*.mp4'): mp4_stem = mp4_file.stem # 生成目录2文件对应的匹配标识(MP4主名去掉第一个字符) match_key = mp4_stem[1:] if match_key in usd_file_map: target_usd = usd_file_map[match_key] new_usd_path = dir2 / f"{mp4_stem}.usd" try: target_usd.rename(new_usd_path) print(f"完成重命名:{target_usd.name} → {new_usd_path.name}") except Exception as e: print(f"重命名失败 [{target_usd.name}]:{str(e)}") else: print(f"未找到匹配文件:{mp4_stem}.usd(需匹配标识:{match_key})")
脚本说明
- 映射预存:先遍历目录2的所有USD文件,建立「去掉下划线的主文件名-文件路径」的映射字典,提升匹配效率
- 精准匹配:遍历目录1的MP4文件,用其主文件名去掉首字符后的字符串作为匹配键,在映射字典中查找对应USD文件
- 异常处理:捕获重命名时的权限、文件已存在等异常,输出明确日志便于排查
- 路径验证:运行前可通过
print(dir1.exists())和print(dir2.exists())确认目录路径是否正确
内容的提问来源于stack exchange,提问作者Megan Darcy
相关产品推荐
相关产品推荐

