Thursday, 23 June 2022

How to create a copy of a file after observing the event using File Listener (watchdog) in Python?

I have below code which is listening to any excel file in one my directory. Below code is working file. However, I would like to modify the code such that as soon as new file arrives in the path it creates a copy of the same file in another folder. Let's say folder name is "today". I am not sure how to create a copy of same file as soon as new event is observed ? The copied file should be of same extension. In this case it will be excel

I am new to OOP so any help is much appreciated!

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

class FileWatcher(PatternMatchingEventHandler):
    patterns = ["*.xlsx"] 

    def process(self, event):
        
       # event.src_path will be the full file path
       # event.event_type will be 'created', 'moved', etc.
       print('{} observed on {}'.format(event.event_type, event.src_path))

    def on_created(self, event):
        self.process(event)

if __name__ == '__main__':
    obs = Observer() 
    obs.schedule(FileWatcher(), path='path/')
    print("Monitoring started....")
    obs.start() # Start watching

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

    obs.join()


from How to create a copy of a file after observing the event using File Listener (watchdog) in Python?

No comments:

Post a Comment