Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run python script when txt file is changed

I am working on a home automation project with a Raspberry Pi 3 and I need to run some python scripts when a txt file changes. Is there a way to watch if the file is changed? (Currently i use a python script which constantly opens the txt and checks if anything changed but its not efficient and it causes problems sometimes. Thanks in advance!

like image 323
Chris Avatar asked May 31 '26 07:05

Chris


1 Answers

If you wanted to report changes to a single file in the local directory called foo.txt you can use watchdog (which is a skin over inotify, or equivalent) like this:

from time import sleep
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Handler(FileSystemEventHandler):
    def on_modified(self, event):
        if event.src_path == "./foo.txt": # in this example, we only care about this one file
            print ("changed")

observer = Observer()
observer.schedule(Handler(), ".") # watch the local directory
observer.start()

try:
    while True:
        sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()
like image 176
Finlay McWalter Avatar answered Jun 03 '26 02:06

Finlay McWalter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!