Skip to main content
 首页 » 编程设计

python之更改 txt 文件时运行 python 脚本

2025年02月15日8birdshome

我正在使用 Raspberry Pi 3 进行家庭自动化项目,我需要在 txt 文件更改时运行一些 python 脚本。有没有办法查看文件是否更改? (目前我使用一个 python 脚本,它不断打开 txt 并检查是否有任何更改,但它效率不高,有时会导致问题。 提前致谢!

请您参考如下方法:

如果您想报告对本地目录中名为 foo.txt 的单个文件的更改,您可以使用 watchdog (这是 inotify 或等价物的皮肤)像这样:

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()