Python watchdog 监控文件夹变化

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


class MyDirEventHandler(FileSystemEventHandler):

    def on_moved(self, event):
        print(event)

    def on_created(self, event):
        print(event)

    def on_deleted(self, event):
        print(event)

    def on_modified(self, event):
        print("modified:", event)


"""
使用watchdog 监控文件的变化
"""
if __name__ == '__main__':
    # 创建观察者对象
    observer = Observer()
    # 创建事件处理对象
    fileHandler = MyDirEventHandler()

    # 为观察者设置观察对象与处理事件对象
    observer.schedule(fileHandler, "C:/test", True)
    observer.start()
    try:
        while True:
            time.sleep(2)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

你可能感兴趣的:(python)