Reputation: 3
I am trying to get the name of a file that changes periodically. I am using watchdog to do this.
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
timestr = time.strftime("%Y.%m.%d-%H.%M.%S")
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
change_log = open('change_log_' + timestr + '.txt', 'aw')
change_log.write('Time the file changed: ' + timestr + '\n')
change_log.close()
if __name__ == "__main__":
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
For some reason this prints out about 62 lines in the "change_log" file. This is not very useful. What I would like to do is to print the name of the file that changed, or store it in a variable to pass to my other module.
Upvotes: 0
Views: 6353
Reputation: 8673
In your example, if you need a file name, it is necessary to replace 'change_log_'
with event.src_path
. See the official code for more details.
You can also see the use of event.src_path
in this answer as I used it in the printout.
Upvotes: 1
Reputation: 1
It looks like the event object that is sent to your handler includes the information that you seek: http://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEvent
Use the src_path
property of the event object that's passed into your FileSystemEvent
subclass handler method to get the filename.
Upvotes: 0