Search code examples
pythonpython-watchdog

Python Watchdog - How to only view when files are created?


From the Watchdog Quickstart, I can see all events such as when a folder is modified, a file deleted, a file created, etc. However, I only want to see when a file has been created. What do I have to change to only see created files?

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

Solution

  • You would need to create your own event handler class based on FileSystemEventHandler. You would override the on_created method to process the event when received.