DEV Community

petercour
petercour

Posted on

2 1

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 watch.py /home/YOURNAME/Downloads  
Enter fullscreen mode Exit fullscreen mode

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

cd Downloads
echo "test" > tmp.txt
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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

Related links:

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
chamarapw profile image
ChamaraPW

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay