Python重命名子子目录遇FileNotFoundError问题排查
问题分析与修复:移动并重命名子子目录时的FileNotFoundError错误
问题描述
我需要制作不含子子目录的数据集,计划将data目录下的子子目录重命名为{父目录名}_{子子目录名}后移至data目录,再删除空父目录。编写嵌套循环代码后运行出现错误:
FileNotFoundError: [WinError 2] 系统找不到指定文件: 'data\1\1_1' -> 'data\1_1'
用户代码如下:
''' In the data/ directory, For each subdirectory For each sub-subdirectory Rename it to '{sub_dir}_{subsub_dir}' # So I know which subdir the subsubdir came from Take the subsub_dir out of the sub_dir, and place it in 'data/' After the inner loop, the subdir should be empty and we can remove it ''' PATH = r'data' # Relative path for s in os.listdir(PATH): subdir_path = os.path.join(PATH, s) for ss in os.listdir(subdir_path): pprint(f'Before: {ss}') ss = f'{s}_{ss}' # pprint(f'After: {ss}') os.rename(os.path.join(subdir_path, ss), os.path.join(PATH, ss)) # os.remove(subdir_path) # Commented out for safety
错误原因
核心问题是你直接覆盖了循环变量ss的值:
- 初始
ss是子子目录的原始名称(比如1),但执行ss = f'{s}_{ss}'后,ss变成了重命名后的新名称(比如1_1) - 此时
os.path.join(subdir_path, ss)拼接出的源路径是data\1\1_1,但这个目录根本不存在——你要移动的原始目录是data\1\1,而非这个新名称的目录,自然触发找不到文件的错误
修复后的代码
保留原始子子目录名称,用单独变量存储新名称,同时增加目录判断和异常处理:
''' In the data/ directory, For each subdirectory For each sub-subdirectory Rename it to '{sub_dir}_{subsub_dir}' # So I know which subdir the subsubdir came from Take the subsub_dir out of the sub_dir, and place it in 'data/' After the inner loop, the subdir should be empty and we can remove it ''' import os from pprint import pprint PATH = r'data' # Relative path for s in os.listdir(PATH): subdir_path = os.path.join(PATH, s) # 跳过非目录项,避免处理data下的文件 if not os.path.isdir(subdir_path): continue for ss in os.listdir(subdir_path): original_path = os.path.join(subdir_path, ss) # 只处理子子目录,跳过文件 if not os.path.isdir(original_path): continue new_name = f'{s}_{ss}' pprint(f'Before: {ss}') pprint(f'After: {new_name}') new_path = os.path.join(PATH, new_name) # 执行重命名+移动操作 os.rename(original_path, new_path) # 删除空父目录,用rmdir而非remove(remove用于删文件) try: os.rmdir(subdir_path) pprint(f"已删除空目录: {subdir_path}") except OSError: pprint(f"目录 {subdir_path} 非空,未删除")
额外优化点
- 添加
os.path.isdir判断,避免误处理data目录下的文件 - 使用
os.rmdir删除空目录,替代原本的os.remove(后者仅适用于文件) - 增加异常捕获,防止父目录因残留文件无法删除时崩溃
内容的提问来源于stack exchange,提问作者hbhutta
相关产品推荐
相关产品推荐

