CodeRocks
CodeRocks

Reputation: 715

Windows OS: Python Watchdog Detect Destination File Path for "Deleted" Files

I have a python script running on Windows using the watchdog python module that is designed to detect file location changes recursively in a folder with folders inside of it. When I move a file within a inner folder outside of its current location, a FileDeleted event occurs rather than a FileMoved. I want to be able to tell what the end location of the file is, which I am able to do on Mac but NOT on Windows. I read this article which suggests that the problem is with Windows.

This is my code:

class Handler(PatternMatchingEventHandler):
    @staticmethod
    if event.event_type == 'created' or event.event_type == 'modified':
          # do something if file created.
    elif event.event_type == 'deleted'
          # do something if file deleted
    elif event.event_type == 'moved':
          # do something if file moved

How do I make the file moved event occur as opposed to the file created and delete events? Or is there a work around that would allow me to treat a DeletedEvent like a MovedEvent by getting the final file path?

Any help would be greatly appreciated!

Upvotes: 1

Views: 1571

Answers (1)

Pablo Vilas
Pablo Vilas

Reputation: 586

Try to define each event separately like this:

def on_created(event):
    print(f"hey, {event.src_path} has been created!")

def on_deleted(event):
    print(f"Someone deleted {event.src_path}!")

def on_modified(event):
    print(f"{event.src_path} has been modified")

def on_moved(event):
    print(f"someone moved {event.src_path} to {event.dest_path}")

my_event_handler.on_created = on_created
my_event_handler.on_deleted = on_deleted
my_event_handler.on_modified = on_modified
my_event_handler.on_moved = on_moved

Anyway I think in this link you will find the iformation you need: https://www.thepythoncorner.com/2019/01/how-to-create-a-watchdog-in-python-to-look-for-filesystem-changes/

Upvotes: 1

Related Questions