pythonpython-watchdog

How to read the file when that file was changed?


I don't know how to use the watchdog script and read file script together.

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 = "C:/watch"

    event_handler = LoggingEventHandler() 
    observer = Observer() 
    observer.schedule(event_handler, path, recursive=True) 
    observer.start() 
    try: 
        while True: 
            time.sleep(1) 
    finally: 
        observer.stop() 
        observer.join()

    file = open('test.txt','r') 
    f = file.readlines()

    newList = [] 
    for line in f: 
        newList.append(line[:-1])

    print(newList)

Solution

  • Your imports are incorrect (syntax error), and so is the if name == "main": test, take another look at the example in https://pypi.org/project/watchdog/. Here's a patched version, plus a couple of changes listed below:

    import sys 
    import time 
    import logging
    from watchdog.observers import Observer
    from watchdog.events import LoggingEventHandler
    
    def on_modified(event_handler):
        print(f'event_handler.src_path={event_handler.src_path}')
    
    if __name__ == "__main__": 
        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S')
    
        path = "C:/watch"
    
        event_handler = LoggingEventHandler() 
        event_handler.on_modified = on_modified
        observer = Observer() 
        observer.schedule(event_handler, path, recursive=True) 
        observer.start() 
        try: 
            while True: 
                time.sleep(1) 
        finally: 
            observer.stop() 
            observer.join()
    

    I added a callback function on_modified (currently does just a print), assigned it to your event handler's on_modified function, removed the editing of the "test.txt" file at the end. You should now put this into the callback function.

    You can see in the callback function that event_handler.src_path is the path to a file that was modified: at that point, you can put the code to read the file.