DEV Community


Posted on

Watchdog for File System in Python

The watchdog module can monitor file system changes. This is a Python module. File system changes happen all the time, saving files, deleting files and so on.

Lets say you monitor the Downloads directory. Well hurry up, how does this work?

Run the monitor script. Say you monitor the Downloads directory on your file system.

python3 /home/YOURNAME/Downloads  

Enter the downloads directory and create a new file in a different terminal tab.

cd Downloads
echo "test" > tmp.txt

The script will tell you the file system has changed

2019-07-17 13:37:32 - Created file: /home/YOURNAME/Downloads/tmp.txt
2019-07-17 13:37:32 - Modified directory: /home/YOURNAME/Downloads
2019-07-17 13:37:32 - Modified file: /home/YOURNAME/Downloads/tmp.txt

The code for this is very simple:

#-*- coding: utf-8 -*-                                                                                                                                              

import sys
import time
import logging
from watchdog.observers import Observer
from import LoggingEventHandler

if __name__ == "__main__":
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
        while True:
    except KeyboardInterrupt:

First import the watchdog modules. Create an Observer object, set it to schedule and recursive. Then start it.

Related links:

Top comments (1)

chamarapw profile image

is there any way to read the content of that text file after this modified event triggered.