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

如何用Python Watchdog API捕获目录变更文件路径到变量?

嘿,我来帮你搞定这个需求!你现在用的LoggingEventHandler其实只是帮你把事件信息打印到日志里,没法直接把路径存成变量供后续使用。咱们得自定义一个事件处理器,这样就能完全掌控拿到的文件路径啦!

解决方法:自定义事件处理器捕获文件路径

核心思路是继承watchdog.events.FileSystemEventHandler,重写专门处理文件创建事件的on_created方法,在这个方法里直接提取并存储文件路径。

完整修改后的代码

import sys
import time
import logging
import shutil
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# 自定义事件处理器类,完全掌控事件逻辑
class FolderMonitorHandler(FileSystemEventHandler):
    def on_created(self, event):
        # 过滤掉文件夹创建事件,只处理文件
        if not event.is_directory:
            # 把文件路径存成字符串变量,后续随便用
            new_file_path = event.src_path
            print(f"捕获到新文件:{new_file_path}")
            
            # 这里写你后续的操作,比如复制文件到目标文件夹
            # 示例:复制到C:\Backup目录
            target_dir = Path("C:\\Backup")
            target_dir.mkdir(exist_ok=True)  # 目标文件夹不存在就自动创建
            try:
                shutil.copy2(new_file_path, target_dir)
                print(f"文件已成功复制到:{target_dir.resolve()}")
            except Exception as e:
                print(f"复制文件出错:{str(e)}")

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
    path = 'C:\\Dell'
    
    # 用自定义处理器替换原来的LoggingEventHandler
    event_handler = FolderMonitorHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

关键细节说明

  • event.src_path就是你要的文件路径字符串,直接赋值给变量new_file_path后,后续的复制、移动、读取等操作都可以基于这个变量实现。
  • event.is_directory用来区分创建的是文件还是文件夹,加上这个判断能避免误处理文件夹的创建事件。
  • 示例里加了文件复制的逻辑,用shutil.copy2可以保留文件的元数据(比如创建时间、修改时间),如果不需要元数据,用shutil.copy也能完成复制。
  • Path("C:\\Backup").mkdir(exist_ok=True)会自动创建目标文件夹,如果文件夹已经存在也不会报错,避免复制时因目录不存在抛出异常。

这样修改后,每次C:\Dell目录下有新文件创建,你都能拿到它的路径变量,想怎么操作都没问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:23:11