davidjbeiler
davidjbeiler

Reputation: 133

Using watchdog python to watch for file, if it see's changes, execute another python script then wait again

import sys
import time
import logging, os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class Watcher:

    DirectoryToWatch = 'C:\\Users\\dbeiler\\Documents\\Visual Studio 2015\\Projects\\New folder\\'

    def __init__(self):
        self.observer = Observer()
    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DirectoryToWatch, recursive=True)
        self.observer.start()
        try:
            while True:
            time.sleep(5)
        except:
            self.observer.stop()
            print ("Error")
            self.observer.join()

class Handler(FileSystemEventHandler):

    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'modified':
            # Take any action here when a file is first created.
            os.system('python writetodata.py')
            sys.exit
            time.sleep(5)


if __name__ == '__main__':
    w = Watcher()
    w.run()

The application works when i copy a file to the location, it will execute my script, however the script keeps cycling, i would like it to stop and wait for another file once its already been written, not sure what im missing

I moved one of my directory folders, and now its writing to my output excel file twice, i assume its because 1.) its being opened, and 2.) its saving.

Upvotes: 0

Views: 2626

Answers (1)

Chris K
Chris K

Reputation: 31

how about looking for a specific object type only like xlsx'?

Upvotes: 1

Related Questions