Menu

1 / 2

Python File Watcher: Trigger Actions When Files Change

DEV Community·Brad·6 months ago
#TRRJgA2u
#python#automation#devops#path#logging
Reading 0:00
15s threshold

Python File Watcher: Trigger Actions When Files Change

The Problem

Manually checking if files changed or running pipelines manually slows development and operations.

The Solution

Build a file watcher that triggers specific actions when files are created, modified, or deleted.

Complete Implementation

from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import time , os , subprocess , logging

logging . basicConfig ( level = logging . INFO )

class SmartFileHandler ( FileSystemEventHandler ): def __init__ ( self ): self . processed = set () # Avoid duplicate events def on_created ( self , event ): if not event . is_directory : self . handle_file ( event . src_path , " created " )

def on_modified ( self , event ): if not event . is_directory : self . handle_file ( event . src_path , " modified " )

def on_deleted ( self , event ): logging . info ( f " Deleted: { event .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.