python – How to monitor changes to a folder?

Question:

How can I monitor and capture changes to folders and files? I intend to use this as part of a service that starts with the system the script would be in .pyw . example:

if(mudou != padrao):
    pass

however I don't know how this script would monitor the changes in this folder, I thought of doing it with sleep() but I don't know if there would be a proper module for this.

Answer:

You can use Watchdog

Install:

> pip install watchdog 

Example:

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

class MyHandler(FileSystemEventHandler):
    def on_any_event(self, event):
        print 'Evento', event.event_type,' caminho:', event.src_path, 'diretorio?', event.is_directory

path = 'C:\\caminho\\desejado\\aqui'
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')
observer = Observer()
observer.schedule(MyHandler(), path, recursive=True)
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()
Scroll to Top