I am trying to monitor a folder using watchdog, the problem is I dont understand why watchdog observer output multiple logs when one event happens. The code I used is shown below, it is a very basic code that I found on the internet.
# import the 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 info
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# Set format for displaying path
path = sys.argv[1] if len(sys.argv) > 1 else '.'
# Initialize logging event handler
event_handler = LoggingEventHandler()
# Initialize Observer
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
# Start the observer
observer.start()
try:
while True:
# Set the thread sleep time
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
2024-08-26 09:38:21 - Created file: .\from\test_folder\testwatchdog.txt
2024-08-26 09:38:21 - Modified directory: .\from\test_folder
2024-08-26 09:38:21 - Modified file: .\from\test_folder\testwatchdog.txt
2024-08-26 09:38:55 - Deleted file: .\from\test_folder\testwatchdog.txt
2024-08-26 09:38:55 - Created file: .\testwatchdog.txt
2024-08-26 09:39:07 - Moved file: from .\testwatchdog.txt to .\testwatchdogs.txt
2024-08-26 09:39:21 - Modified file: .\testwatchdogs.txt
2024-08-26 09:39:21 - Modified file: .\testwatchdogs.txt
2024-08-26 09:39:21 - Modified file: .\testwatchdogs.txt
2024-08-26 09:39:39 - Modified file: .\testwatchdogs.txt
2024-08-26 09:39:39 - Modified file: .\testwatchdogs.txt
2024-08-26 09:39:39 - Modified file: .\testwatchdogs.txt
The last 6lines, what i did is just modified twice
I have tried some other methods, but it still do the same thing. I am not sure where the problem is.
Look at this answer. The gist of it is that some tools that modify files do multiple operations on the file that the underlying operating system is reporting to you.