Monitoring File System Changes (Watchdog)
flowchart TD
A["you save a file"] --> B["the OS emits events"]
B --> C["created"]
B --> D["modified -- often more than once"]
B --> E["moved -- editors write a temp file then move it"]
C --> F["your handler fires"]
D --> F
E --> F
F --> G{"is the file finished being written?"}
G -->|"maybe not"| H["reading it now can give a partial file"]
G --> I["debounce: wait for quiet, then act once"]
H --> I
I --> J["retry on PermissionError -- the writer may still hold it"]
What watchdog does
Section titled “What watchdog does”watchdog lets you react to:
- file created
- file modified
- file deleted
This is useful for:
- auto-processing new files
- syncing folders
Example watcher
Section titled “Example watcher”from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Handler(FileSystemEventHandler):
def on_created(self, event):
if event.is_directory:
return
print("created:", event.src_path)
if __name__ == "__main__":
import time
path = "."
observer = Observer()
observer.schedule(Handler(), path=path, recursive=True)
observer.start()
print("watching", path)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()- Install dependency:
watchdog - Keep handlers fast (offload heavy work)
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading