1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import os import re
def rename_files(directory): """ 重命名目录中符合模式('...', '...').txt的文件为第一个参数+.txt格式
参数: directory (str): 要遍历的目录路径 """ pattern = re.compile(r"^\('([^']*)',\s*'([^']*)'\)\.txt$")
for root, _, files in os.walk(directory): for filename in files: match = pattern.match(filename) if match: new_name = f"{match.group(1)}.txt" old_path = os.path.join(root, filename) new_path = os.path.join(root, new_name)
try: os.rename(old_path, new_path) print(f"成功重命名: {filename} -> {new_name}") except FileExistsError: print(f"跳过重命名: {new_name} 已存在") except Exception as e: print(f"处理 {filename} 时出错: {str(e)}")
if __name__ == "__main__": import sys
target_dir = "/data/Competitions/labels/train" if not os.path.isdir(target_dir): print(f"错误: {target_dir} 不是有效目录") sys.exit(1)
rename_files(target_dir)
|