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!
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With