Change language

Create a watchdog timer in Python to look for changes in the filesystem

| | |

Many times a file must be processed during its creation or modification. This can be done by following the changes in a specific directory. There are many ways in python to keep track of changes made to a directory. One such way is to use the watchdog module. As the name suggests, this module monitors the given directory and can notify if a file is created or modified.

Required Modules

  • Guard Dog
    To install the watchdog, run this command in a terminal.
     pip install watchdog 
  • logging
    It comes with Python, so no need install it externally.

Now let’s dive into the code that will log all the logged changes. This code will only log changes checked in to the current directory.

# import modules

import sys

import time

import logging

from watchdog.observers import Observer

from watchdog.events import LoggingEventHandler

  

if __ name__ = = " __ main__ " :

  # Set the format for logging information

logging.basicConfig (level = logging.INFO,

format = ’% (asctime) s -% (message) s’ ,

datefmt = ’% Y-% m-% d% H:% M:% S’ )

 

# Install format for displaying the path

path = sys.argv [ 1 ] if len (sys.argv)"  1 else ’.’

 

# Initialize registration event handler

event_handler = LoggingEventHandler ()

 

# Initialize Observer

observer = Observer ()

observer.schedule (event_handler, path, recursive = True )

 

# Start observer

observer.start ()

try :

while True :

  # Set stream timeout

time.sleep ( 1 )

  except KeyboardInterrupt:

observer.stop ()

observer.join ()

Output:

The above code will log all changes registered to the directory. If you want to make changes while creating or modifying a file, you can do so using the following code.

# import time module, Observer, FileSystemEventHandler

import time

from watchdog.observers import Observer

from watchdog.events import FileSystemEventHandler

 

 

class OnMyWatch:

# Set directory to watch

watchDirectory = "/ give / the / address / of / directory"

 

def __ init __ ( self ):

self .observer = Observer ()

  

  def run ( self ):

event_handler = Handler ()

  self . observer.schedule (event_handler, self . watchDirectory, recursive = True )

  self . observer .start ()

try :

while True :

time.sleep ( 5 )

except :

  self . observer.stop ()

  print ( "Observer Stopped" )

  

  self . observer.join ()

 

 

class Handler (FileSystemEventHandler):

 

  @ staticmethod

def on_any_event (event):

if event.is_directory:

  return None

  

elif event.event_type = = ’created’ :

# The event was created, you can process it now

print ( "Watchdog received created event -% s." % event.src_path)

elif event.event_type = = ’modified’

# The event has been changed, you can handle it now

print ( " Watchdog received modified event -% s. " % event.src_path)

 

 

if __ name__ = = ’ __main__’ :

watch = OnMyWatch ()

watch.run ()

Output:

Create a watchdog timer in Python to look for changes in the filesystem _files: Questions

Create a watchdog timer in Python to look for changes in the filesystem File handling: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method