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

使用Python的filecmp库删除重复文件报FileNotFoundError如何解决

错误原因
  • os.listdir()仅返回目标路径下的文件名/目录名,不会携带父级路径
  • 你的脚本运行时的工作目录是脚本所在的C:\Users\DELL\PycharmProjects\pythonBasics\File Handling,而非存放图片的F:\filetestpython,直接传入文件名2.JPG时,Python会在当前工作目录下查找该文件,因此触发找不到文件的报错。
修复后的实现代码
import os
import filecmp

# 提前定义目标文件夹路径,避免重复硬编码出错
target_dir = r'F:\filetestpython'
# 基准文件的完整绝对路径
base_file = os.path.join(target_dir, '2.JPG')

# 先判断基准文件是否存在,避免异常
if not os.path.exists(base_file):
    print("基准文件2.JPG不存在,请检查路径")
    exit()

# 遍历目标文件夹下的所有文件
for filename in os.listdir(target_dir):
    # 拼接得到当前文件的完整绝对路径
    current_file = os.path.join(target_dir, filename)
    # 跳过基准文件本身,且只处理文件(跳过子目录)
    if current_file == base_file or not os.path.isfile(current_file):
        continue
    # 用完整路径进行文件比对
    if filecmp.cmp(base_file, current_file, shallow=False):
        # 建议先替换为print测试,确认要删除的文件无误后再换成os.remove
        # print(f"发现重复文件,将删除:{current_file}")
        os.remove(current_file)
补充说明
  • 比对时添加了shallow=False参数,会读取文件实际内容进行比对,而非仅靠文件元数据判断,准确率更高
  • 代码增加了基准文件存在性校验,同时跳过了子目录的处理,避免出现额外异常
  • 正式删除前可以先注释掉os.remove行,打开print的注释,先预览要删除的文件列表,确认无误后再执行删除操作,避免误删重要文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:36:02