# yaml_processor.py import yaml import pandas as pd import os class YAMLProcessor: def __init__(self, yaml_path="local_data.yaml"): """ 處理 YAML 讀寫的類別。 Args: yaml_path (str): YAML 檔案路徑。 """ self.yaml_path = yaml_path # 如果檔案不存在,就建立一個空的 if not os.path.isfile(self.yaml_path): with open(self.yaml_path, "w", encoding="utf-8") as f: yaml.safe_dump([], f, allow_unicode=True) def load_local_data(self): """ 從 YAML 中讀取資料並轉成 DataFrame。 Returns: pd.DataFrame: local_data.yaml 內容。 """ with open(self.yaml_path, "r", encoding="utf-8") as f: data = yaml.safe_load(f) if data is None: data = [] df = pd.DataFrame(data) return df def save_local_data(self, df): """ 將 DataFrame 內容回存到 YAML。 Args: df (pd.DataFrame): 要存回 YAML 的 DataFrame。 """ # 將 df 轉成 list[dict] 方便寫回 YAML data_list = df.to_dict(orient="records") with open(self.yaml_path, "w", encoding="utf-8") as f: yaml.safe_dump(data_list, f, allow_unicode=True)