Python递归遍历目录删除文件名日期重复的冗余图片
重复日期段图片清理方案
核心逻辑
- 递归遍历目标目录下所有层级子文件夹
- 基于原有文件名排序规则,逐文件提取开头8位日期段
- 同一日期段仅保留排序后第一个匹配的文件,后续同日期文件判定为冗余
- 增加试运行开关,先核对待删文件列表再执行真实删除,避免误操作
- 自动跳过不符合
DATE_TIME_Visual.tif命名规则的文件
初始参考代码与测试样本
初始编写的单目录文件打印代码如下:
from os import listdir my_current_image_path = r'../Desktop/Images/city1' for f in sorted(listdir(my_current_image_path)): print(f)
运行得到的排序后文件列表:
20190602_051825_Visual.tif 20190604_052001_Visual.tif 20190605_044324_Visual.tif 20190605_052033_Visual.tif 20190607_044351_Visual.tif 20190607_051806_Visual.tif 20190611_051850_Visual.tif
样本中需删除的冗余文件为同日期下排序靠后的2个文件:20190605_052033_Visual.tif、20190607_051806_Visual.tif
可直接运行的实现代码
import os # 配置项 root_path = r'../Desktop/Images' run_delete = False # 首次运行保持False,仅打印待删文件,确认无误后改为True执行删除 target_suffix = ('.tif', '.tiff') for dir_path, _, file_names in os.walk(root_path): # 过滤目标后缀文件,按文件名排序 sorted_files = sorted([f for f in file_names if f.lower().endswith(target_suffix)]) prev_date = None for file in sorted_files: # 提取前8位作为日期段 date_part = file[:8] # 校验日期段格式,不符合规则的文件直接跳过 if len(date_part) != 8 or not date_part.isdigit(): print(f"跳过非规则命名文件: {os.path.join(dir_path, file)}") prev_date = None continue # 日期重复则判定为冗余 if date_part == prev_date: full_path = os.path.join(dir_path, file) print(f"冗余重复文件: {full_path}") if run_delete: os.remove(full_path) print(f"已删除: {full_path}") else: prev_date = date_part
使用说明
- 首次运行必须保持
run_delete = False,控制台会打印所有识别到的冗余文件,逐一核对列表和预期一致后,再将参数改为True执行删除 - 代码通过
os.walk实现全目录递归遍历,会自动处理根目录下所有层级的子文件夹,不需要手动切换单目录路径 - 同日期下保留排序靠前的文件,和原有代码的排序逻辑完全一致,即保留同日期中拍摄时间更早的影像文件
- 仅处理后缀为tif/tiff的文件,不会误误操作目录下其他格式的文件
内容的提问来源于stack exchange,提问作者Scott
相关产品推荐
相关产品推荐

