Python新手求助:实现本地JSON文件变更监听与控制台输出功能
实现JSON文件监控与变更检测的完整方案
嘿,作为Python新手,咱们一步步来搞定这个需求!要实现持续监控JSON文件并输出变更内容,主要需要两个核心能力:实时监控文件系统变化和对比JSON数据差异,下面是完整的实现方案:
第一步:安装依赖库
我们需要用watchdog这个库来监听文件系统的变化,先通过pip安装:
pip install watchdog
完整代码实现
import time import json from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class JSONFileMonitor(FileSystemEventHandler): def __init__(self, file_path): self.file_path = file_path # 初始化时读取初始JSON数据,作为对比基准 self.last_data = self._load_json() def _load_json(self): """读取并解析JSON文件,处理常见异常""" try: with open(self.file_path, 'r', encoding='utf-8') as f: return json.load(f) except FileNotFoundError: print(f"警告:未找到目标文件 {self.file_path},将创建空数据作为初始基准") return {} except json.JSONDecodeError as e: print(f"JSON解析错误: {e},当前文件内容不符合JSON格式") return {} def _compare_data(self, new_data): """对比新旧JSON数据,输出具体变更内容""" # 检查原有键的修改或删除 for key, old_value in self.last_data.items(): if key in new_data: if new_data[key] != old_value: print(f"change detected at key {key} and value {new_data[key]}.") else: print(f"key {key} has been removed.") # 检查新增的键 for key, new_value in new_data.items(): if key not in self.last_data: print(f"new key {key} added with value {new_value}.") # 更新基准数据为最新版本 self.last_data = new_data def on_modified(self, event): # 只处理目标文件的修改事件,忽略目录和其他文件 if not event.is_directory and event.src_path == self.file_path: # 延迟0.1秒,避免文件还没完全保存就读取导致的解析错误 time.sleep(0.1) new_data = self._load_json() if new_data != self.last_data: self._compare_data(new_data) if __name__ == "__main__": # 替换成你的JSON文件实际路径 json_file_path = "test.json" event_handler = JSONFileMonitor(json_file_path) observer = Observer() # 监控文件所在的目录(不需要递归) observer.schedule(event_handler, path=".", recursive=False) observer.start() print(f"开始监控JSON文件: {json_file_path},按下Ctrl+C可停止监控") try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
代码拆解与使用说明
1. 核心逻辑说明
- 自定义事件处理器:继承
FileSystemEventHandler重写on_modified方法,只响应目标JSON文件的修改事件 - JSON读取与异常处理:
_load_json方法封装了文件读取和解析逻辑,处理了文件不存在、格式错误等常见问题,避免程序直接崩溃 - 差异对比:
_compare_data方法会逐一对比新旧JSON的键值对,不仅能检测值的修改,还能识别键的新增和删除
2. 测试示例
比如你的初始test.json内容是:
{ "a":2, "b":3 }
- 修改
a的值为3并保存,控制台会输出:change detected at key a and value 3. - 新增键
c:4,会输出:new key c added with value 4. - 删除键
b,会输出:key b has been removed.
3. 小提示
- 记得把代码里的
json_file_path替换成你实际的JSON文件路径 - 如果你的JSON文件体积很大,可以优化差异对比逻辑,但这个版本对新手来说足够简单实用
- 监控的是文件所在的目录,其他文件修改不会触发逻辑,因为我们做了文件路径判断
内容的提问来源于stack exchange,提问作者Vikas Kanna
相关产品推荐
相关产品推荐

