将子文件夹文件移至目标文件夹遇FileNotFoundError问题求助
问题分析与解决办法
错误原因
出现FileNotFoundError常见原因有这几个:
- 目标目录
negatives未创建:os.replace()不会自动生成目标目录,若目录不存在直接移动就会报错。 - 遍历到非目录项:
os.listdir()会返回目标路径下所有条目(含文件、符号链接等),如果lfw目录下存在非子目录的文件,内层os.listdir()会因找不到有效目录报错。 - 文件名重复:不同子目录下的同名文件,先移动的会占据目标位置,后续移动同名文件时也可能触发错误(当前错误提示更偏向路径问题)。
修复后的代码
import os source_root = '/content/drive/MyDrive/Dev/FaceRec/lfw' target_dir = '/content/drive/MyDrive/Dev/FaceRec/negatives' # 提前创建目标目录,已存在则不报错 os.makedirs(target_dir, exist_ok=True) # 遍历源目录下的所有条目,仅处理子目录 for entry in os.listdir(source_root): entry_path = os.path.join(source_root, entry) if not os.path.isdir(entry_path): continue # 遍历子目录下的文件,跳过嵌套子目录 for file in os.listdir(entry_path): file_path = os.path.join(entry_path, file) if not os.path.isfile(file_path): continue target_path = os.path.join(target_dir, file) # 处理同名文件:自动重命名避免覆盖 counter = 1 while os.path.exists(target_path): name, ext = os.path.splitext(file) target_path = os.path.join(target_dir, f"{name}_{counter}{ext}") counter += 1 os.replace(file_path, target_path)
关键改进点
- 用
os.makedirs(target_dir, exist_ok=True)确保目标目录存在,避免路径不存在的错误。 - 增加
os.path.isdir()判断,只处理源目录下的子目录,跳过非目录项。 - 增加
os.path.isfile()判断,跳过子目录里的嵌套目录。 - 新增同名文件处理逻辑,自动给重复文件名加后缀,避免覆盖或移动失败。
内容的提问来源于stack exchange,提问作者Nocry
相关产品推荐
相关产品推荐

