I am trying to watch a single file for modification in a directory.
This file is 'csv' and is generated by the google form responses. It gets updated as soon as a new response is registered and this new entry needs to be used to create new objects and stored in DB.
As a test I tried updating a sample .txt file in a directory which contained several folders. To achieve the task I used watchdog and tried logging the modification events for the folder.
The folder structure is as follows
-test
|--a.txt
|--fileRandom.txt
.
.
I tried logging the activity using the following code
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from datetime import datetime, timedelta
class Handler(FileSystemEventHandler):
def on_modified(self, event):
print(f'event type: {event.event_type} path : {event.src_path}')
if __name__ == "__main__":
path = 'test/wdogfolder'
event_handler = Handler()
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Upon editing a.txt I get the following log.
event type: modified path : /test/wdogfolder
event type: modified path : /test/wdogfolder/.goutputstream-CP5LX0
event type: modified path : /test/wdogfolder/.goutputstream-CP5LX0
event type: modified path : /test/wdogfolder
Now if another file were to be edited inside the same folder then the log is as follows.
event type: modified path : /test/wdogfolder
event type: modified path : /test/wdogfolder/.goutputstream-J2YCX0
event type: modified path : /test/wdogfolder/.goutputstream-J2YCX0
event type: modified path : /test/wdogfolder
I was hoping of making use src_path to decipher which file changed and thus a simple 'if' statement would have been enough to tackle the problem statement.
But now how do I handle the modification of only a.txt since the path doesn't seem to mention the file name which gets modified.
TIA!
Edit
I am working on ubuntu 18.04. The same code seems to work on windows in the expected way. What might the reason behind that be? And how to circumvent this issue?
question from:
https://stackoverflow.com/questions/65830002/watching-a-single-file-in-a-folder-for-modification-using-watchdog 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…