Introduction to Python file monitoring library watchdogs
With the widespread use of Python in various application fields, its ecological environment continues to flourish, especially the birth of various third-party libraries, which greatly enriches the developer's toolbox. Among many libraries, watchdog, as an efficient file system monitoring library, provides great convenience for real-time response to various events in the file system (such as file creation, modification, deletion, etc.). Watchdog can play an important role in development scenarios where project file changes are needed to trigger automated construction, or in operation and maintenance tasks such as logging and file backup.
File resource monitoring
Installation: pip install watchdog
watchdog supports cross-platform file resource monitoring, and can detect changes in files and folders in designated folders. When there are different changes (addition, delete, and modify), corresponding processing can be performed.
from time import sleep, strftime from import Observer from import FileSystemEventHandler class FileMonitoring(FileSystemEventHandler): # event.is_directory determines whether it is a directory operation def on_modified(self, event): # Triggered when a file or folder is modified (new, deleted, and modifying files or folders will be monitored as folder modifications) tm = strftime("%Y-%m-%d %H:%M:%S") print(f'{tm} Modify folder{event.src_path}') def on_created(self, event): # Triggered when a file or directory is created tm = strftime("%Y-%m-%d %H:%M:%S") if event.is_directory: print(f'{tm} Create a folder{event.src_path}') else: print(f'{tm} Create a file{event.src_path}') def on_deleted(self, event): # Triggered when a file or directory is deleted tm = strftime("%Y-%m-%d %H:%M:%S") if event.is_directory: print(f'{tm} Delete folder{event.src_path}') else: print(f'{tm} Delete files{event.src_path}') def on_moved(self, event): # The directory creation and deletion operation is regarded as a move operation by Watchdog, so it can be captured by the on_moved method, and renaming can also be captured by this. tm = strftime("%Y-%m-%d %H:%M:%S") if event.is_directory: print(f'{tm} Rename folder:Folders{event.src_path} Rename to {event.dest_path}') else: print(f'{tm} Rename the file:document{event.src_path} Rename to {event.dest_path}') class MyFileMonitor(): def __init__(self): self.event_handler = FileMonitoring() # Initialize event handler instance def sever(self, watched_dir, recursive: bool = True): ''' :param watched_dir: .schedule method sets the directory path and event handler to be monitored :param recursive: recursive=True parameter to recursively monitor all subdirectories within the directory :return: ''' = Observer() # Initialize the observer (self.event_handler, watched_dir, recursive=recursive) # Associate the event handler to the observer return def run(self, watched_dir, recursive: bool = True): ''' Start the observer and enter an infinite loop until the user presses Ctrl+C to interrupt the program. () and () to correctly stop and clean observer resources. ''' observer = (watched_dir, recursive) () try: while True: sleep(.1) except KeyboardInterrupt: () ()
Monitor folder addition, deletion, and modification
In Python,watchdog
The library does provide convenient ways to monitor the addition, deletion, modification, and renaming of folders and their internal files. Here is a simple example showing how to usewatchdog
To listen to these events in a folder
import time from import Observer from import FileSystemEventHandler # Define event handler classclass MyHandler(FileSystemEventHandler): def on_modified(self, event): print(f'File modified: {event.src_path}') def on_created(self, event): print(f'File created: {event.src_path}') def on_deleted(self, event): print(f'File deleted: {event.src_path}') # For folder creation and deletion operations, please note: # Directory level events can be captured by the on_moved method, because creating and deleting directories also manifest as moving events def on_moved(self, event): if event.is_directory: what = "Directory" else: what = "File" print(f'{what} moved: {event.src_path} to {event.dest_path}') # Initialize event handler instanceevent_handler = MyHandler() # Specify the folder path to monitorwatched_dir = '/path/to/watch' # Initialize the observerobserver = Observer() # Associate the event handler to the observer(event_handler, watched_dir, recursive=True) # Start the observer() print(f'Starting to watch {watched_dir} for file system events...') try: while True: (1) except KeyboardInterrupt: () ()
In this example, the MyHandler class inherits FileSystemEventHandler and implements several methods to handle different file system events. The on_modified method is triggered when the file is modified, on_created is triggered when the file or directory is created, and on_deleted is triggered when the file or directory is deleted. For directory creation and deletion operations, since Watchdog treats them as move operations, it is snapped through the on_moved method and checks the event.is_directory property to distinguish whether it is a file or a directory.
The directory path and event handler to be monitored are set by the method, and the recursive=True parameter is set to recursively monitor all subdirectories in the directory.
Finally, start the observer and enter an infinite loop until the user presses Ctrl+C to interrupt the program. () and () are called to correctly stop and clean the observer resources.
This is the article about python using watchdog to implement file resource monitoring. For more related contents of python watchdog file resource monitoring, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!