How to monitor changes in a folder?

Asked

Viewed 706 times

3

How can I monitor and capture changes in 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 do not know how to monitor the changes of this folder, I thought to do with the sleep() but I don’t know if there would be a proper module for it.

1 answer

2

You can use the 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()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.