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

Python使用os.remove()删除文件夹内文件时报FileNotFoundError如何解决

问题核心原因
  • os.listdir()返回的是目标目录下的纯文件名,不带任何路径前缀
  • 待删除的文件存储在directory/color/size/speed三级子目录下,直接将纯文件名传入os.remove()时,程序会默认在脚本当前运行的工作目录下查找文件,找不到对应文件就会抛出FileNotFoundError
修正后的代码
import os
directory = 'source_folder'

for color in colors:
    for size in sizes:
        for speed in speeds:
            sub_dir = os.path.join(directory, color, size, speed)
            for file in os.listdir(sub_dir):
                if "p_1" not in file:
                    # 拼接得到文件的完整路径后再执行删除
                    full_path = os.path.join(sub_dir, file)
                    # 可选:增加文件类型校验,避免误删子目录
                    if os.path.isfile(full_path):
                        os.remove(full_path)
注意事项
  • 正式执行删除前,可以先把os.remove(full_path)替换为print(full_path),验证待删除文件的路径是否正确,避免误删
  • 若目录层级不固定,也可以用os.walk()遍历所有层级的文件,减少嵌套循环的代码量

内容的提问来源于stack exchange,提问作者LostinSpatialAnalysis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:36:05