watchdog monitoring file for changes watchdog monitoring file for changes python python

watchdog monitoring file for changes


Instead of LoggingEventHandler define your handler:

#!/usr/bin/pythonimport timefrom watchdog.observers import Observerfrom watchdog.events import FileSystemEventHandlerclass MyHandler(FileSystemEventHandler):    def on_modified(self, event):        print(f'event type: {event.event_type}  path : {event.src_path}')if __name__ == "__main__":    event_handler = MyHandler()    observer = Observer()    observer.schedule(event_handler, path='/data/', recursive=False)    observer.start()    try:        while True:            time.sleep(1)    except KeyboardInterrupt:        observer.stop()    observer.join()

on_modified is called when a file or directory is modified.


Here's a snippet to prevent it running twice as others have commented in @alecxe answer:

from datetime import datetime, timedeltaclass MyHandler(FileSystemEventHandler):    def __init__(self):        self.last_modified = datetime.now()    def on_modified(self, event):        if datetime.now() - self.last_modified < timedelta(seconds=1):            return        else:            self.last_modified = datetime.now()        print(f'Event type: {event.event_type}  path : {event.src_path}')        print(event.is_directory) # This attribute is also available


Instead of datetime, you may go with the src_path check logic since if the logic after the checking more than 1-second datetime logic will fail.

class EventHandler(FileSystemEventHandler):    def __init__(self):        self.src_path = ''    def on_modified(self, event):        if self.src_path == event.src_path:            return        else:            self.src_path = event.src_path        logger.info(f"{event.event_type} occured on file {self.src_path}")        #your long processing logics goes here.