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
相关产品推荐
相关产品推荐

