Python如何监控文件夹新增图片并批量按Excel提取的发动机号重命名
文件夹新增JPG图片自动批量重命名实现方案
前置依赖安装
需要先安装文件监听和Excel读取依赖:
pip install watchdog pandas openpyxl
核心实现逻辑
- 基于
watchdog实时监听文件夹新增文件事件,有新JPG上传时自动触发处理流程 - 维护已处理文件集合,避免文件重复重命名
- 批量处理指定时间窗口内的所有新增文件,重命名时自动加序号避免同名冲突
- 新增文件处理前增加延迟等待,确保文件上传完成无读写锁
完整代码
import os import time import pandas as pd from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # 配置参数 FOLDER_PATH = r'C:\Users\folder\path\for\images' EXCEL_PATH = "g-ng.xlsx" PROCESS_WINDOW = 60 # 处理1分钟内的新增文件,单位秒 WAIT_UPLOAD_TIME = 3 # 等待文件上传完成的时间,单位秒 # 记录已处理过的文件,避免重复操作 processed_files = set() class ImageHandler(FileSystemEventHandler): def on_created(self, event): # 只处理jpg后缀的文件 if not event.is_directory and event.src_path.lower().endswith('.jpg'): # 等待文件上传完成,避免读取到未写完的文件 time.sleep(WAIT_UPLOAD_TIME) self.process_new_images() def process_new_images(self): global processed_files current_time = time.time() # 获取当前文件夹内所有jpg文件 all_jpgs = [os.path.join(FOLDER_PATH, f) for f in os.listdir(FOLDER_PATH) if f.lower().endswith('.jpg')] # 筛选出时间窗口内的未处理新文件 new_files = [] for f in all_jpgs: ctime = os.path.getctime(f) if current_time - ctime < PROCESS_WINDOW and f not in processed_files: new_files.append(f) if not new_files: return # 读取最新的engine编号 df = pd.read_excel(EXCEL_PATH) base_engine_no = str(df['engine_no'].iloc[-1]) # 批量重命名,多文件自动加序号后缀 for idx, old_path in enumerate(new_files): # 处理单文件和多文件后缀 if len(new_files) == 1: new_name = f"{base_engine_no}.jpg" else: new_name = f"{base_engine_no}_{idx+1}.jpg" new_path = os.path.join(FOLDER_PATH, new_name) # 避免重名覆盖 counter = 1 while os.path.exists(new_path): new_name = f"{base_engine_no}_{counter}.jpg" new_path = os.path.join(FOLDER_PATH, new_name) counter += 1 os.rename(old_path, new_path) processed_files.add(new_path) print(f"重命名完成:{os.path.basename(old_path)} -> {new_name}") if __name__ == "__main__": # 初始化时先把现有文件加入已处理集合,避免回溯重命名旧文件 for f in os.listdir(FOLDER_PATH): if f.lower().endswith('.jpg'): processed_files.add(os.path.join(FOLDER_PATH, f)) # 启动文件监听 event_handler = ImageHandler() observer = Observer() observer.schedule(event_handler, FOLDER_PATH, recursive=False) observer.start() print(f"已启动文件夹监听,正在监控{FOLDER_PATH}的新增JPG文件...") try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
注意事项
- 代码运行后会持续后台监听,关闭命令行窗口即可停止运行
- 可根据实际上传速度调整
WAIT_UPLOAD_TIME参数,避免大文件上传未完成就触发重命名报错 - 可修改
PROCESS_WINDOW参数调整批量处理的时间窗口范围 - 重命名时如果遇到同名文件会自动追加数字后缀,不会覆盖已有文件
内容的提问来源于stack exchange,提问作者suhas
相关产品推荐
相关产品推荐

