DEV Community

loading...

Watchdog for File System in Python

petercour
・2 min read

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 watch.py /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:

#!/usr/bin/python3  
#-*- coding: utf-8 -*-                                                                                                                                              

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

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        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)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

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

Related links:

Discussion (1)

Collapse
chamarapw profile image
ChamaraPW

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