Skip to main content

How to monitor file changes in Python

How to monitor file changes in Python.

Here's a step-by-step tutorial on how to monitor file changes in Python using the watchdog library:

Step 1: Install the watchdog library

Before we begin, make sure you have the watchdog library installed. You can install it using pip by running the following command:

pip install watchdog

Step 2: Import the necessary modules

To get started, import the required modules from the watchdog library and other necessary libraries:

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

Step 3: Create a custom event handler

Next, create a custom event handler class that inherits from FileSystemEventHandler. This class will define the behavior when specific events occur, such as file creation, modification, or deletion:

class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
# This method will be called for any file change event
if event.is_directory:
return
if event.event_type == 'created':
print(f"File created: {event.src_path}")
elif event.event_type == 'modified':
print(f"File modified: {event.src_path}")
elif event.event_type == 'deleted':
print(f"File deleted: {event.src_path}")

In the above example, we've defined the behavior for three types of events: file creation, modification, and deletion. You can customize this logic based on your specific requirements.

Step 4: Create an observer and start monitoring

Now, create an instance of the Observer class and attach the event handler to it. Then, specify the directory or file you want to monitor:

if __name__ == "__main__":
event_handler = MyHandler()
observer = Observer()
path = '/path/to/directory' # Replace with your desired directory or file path
observer.schedule(event_handler, path, recursive=True)
observer.start()

Make sure to replace '/path/to/directory' with the actual path of the directory or file you want to monitor. Setting recursive=True allows monitoring of all subdirectories as well.

Step 5: Keep the program running

To keep the program running and continue monitoring for file changes, add an infinite loop:

    try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()

The loop ensures that the program doesn't terminate immediately and allows it to keep monitoring for file changes. Press Ctrl + C to stop the program.

Step 6: Run the code

Save the Python script and run it using the Python interpreter. You should now see the program monitoring the specified directory or file for any changes. Whenever a file is created, modified, or deleted, the corresponding message will be printed to the console.

That's it! You have successfully implemented file change monitoring in Python using the watchdog library. Feel free to modify the event handler logic based on your specific requirements.