Skip to content
Advertisement

Making a program which detects changes in a particular dictionary, and if changes are there then starts the next code

I want to create a program that detects a change in a particular dictionary and if the change is there starts the next code.

By the help of Google found this code: (below is greeksforgeeks code)

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
  
  
class OnMyWatch:
    # Set the directory on watch
    watchDirectory = "/give / the / address / of / directory"
  
    def __init__(self):
        self.observer = Observer()
  
    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.watchDirectory, recursive = True)
        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print("Observer Stopped")
  
        self.observer.join()
  
  
class Handler(FileSystemEventHandler):
  
    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None
  
        elif event.event_type == 'created':
            # Event is created, you can process it now
            print("Watchdog received created event - % s." % event.src_path)
        elif event.event_type == 'modified':
            # Event is modified, you can process it now
            print("Watchdog received modified event - % s." % event.src_path)
              
  
if __name__ == '__main__':
    watch = OnMyWatch()
    watch.run()

It works fine but the problem is it works in loop.

Advertisement

Answer

Here’s a more simpler:

import os
path=r'yourpath'
b=os.listdir(path)
path_len_org=int(len(b))
while True:
      b=os.listdir(path)
      path_len_final=int(len(b))
      if path_len_org<path_len_final:
              print("A file is added")
              break
      if path_len_org>path_len_final:
              print("A file is removed")
              break
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement