You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将子文件夹文件移至目标文件夹遇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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:10:31