3

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!

3
  • 2
    Watchdog should tell you when there are file changes Commented Jun 22, 2017 at 16:23
  • Is the txt file changing predictible? Commented Jun 22, 2017 at 16:46
  • No, the client changes the value when he wants. Commented Jun 24, 2017 at 11:52

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.