python watchdog 监测到文件重命名

Python Watchdog 库可以监测到文件重命名操作。当您设置一个 Watchdog 监视器来监控指定目录时,它会捕获包括文件重命名在内的各种文件系统事件。以下是如何使用 Watchdog 来检测文件重命名事件的示例:

首先,确保您已经安装了 Watchdog 库。如果尚未安装,可以通过 pip 安装:

 

bash

pip install watchdog

 

然后,您可以创建一个简单的 Python 脚本,使用 Watchdog 的 Observer 类和自定义的 FileSystemEventHandler 子类来监听文件重命名事件。下面是一个示例脚本:

 

python

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class RenameHandler(FileSystemEventHandler):
    def on_moved(self, event):
        """
        Handle the file moved (i.e., renamed) event.
        
        Args:
            event (FileMovedEvent): An instance of `FileMovedEvent`, containing information about the renamed file.
        """
        if event.is_directory:
            print(f"Directory {event.src_path} was renamed to {event.dest_path}")
        else:
            print(f"File {event.src_path} was renamed to {event.dest_path}")


if __name__ == "__main__":
    # Specify the directory to watch
    watch_dir = "/path/to/watch"

    # Create the observer and set up the event handler
    observer = Observer()
    event_handler = RenameHandler()

    # Schedule the observer to watch the directory and run the event handler
    observer.schedule(event_handler, watch_dir, recursive=True)
    observer.start()

    print(f"Watching directory '{watch_dir}' for file rename events. Press Ctrl+C to quit.")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

在这个示例中:

  1. 我们定义了一个名为 RenameHandler 的类,继承自 FileSystemEventHandler。这个类覆盖了 on_moved 方法,该方法会在文件或目录被重命名时被调用。event 参数包含了关于重命名操作的详细信息,如原始路径(event.src_path)和新路径(event.dest_path)。

  2. 主程序部分创建了一个 Observer 实例,并设置了事件处理器为 RenameHandler 对象。然后使用 observer.schedule 方法指定要监视的目录(替换 /path/to/watch 为实际路径)以及是否递归监视子目录(recursive=True 表示监视子目录)。

  3. 启动观察器 (observer.start()) 并进入一个无限循环,等待用户按 Ctrl+C 终止程序。在循环中,程序休眠 1 秒,以避免消耗过多 CPU 资源。当接收到 KeyboardInterrupt(用户按下 Ctrl+C)时,停止观察器并等待所有待处理事件完成 (observer.join()).

运行此脚本后,每当指定目录下发生文件或目录重命名操作时,程序将打印出有关重命名事件的信息。您可以根据实际需求,在 on_moved 方法中添加自定义逻辑来处理这些事件,如更新数据库记录、触发其他任务等。

实现效果 

第一个箭头说明程序运行成功

第二个箭头说明检测到文件重命名了,将os.py修改为了os1.py

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三希

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值