import yaml import os class Config: def __init__(self, filename="config.yaml"): self.filename = filename self.config = self.load() def load(self): # 获取config.py文件所在的目录 config_dir = os.path.dirname(os.path.abspath(__file__)) # 构建配置文件的完整路径 config_path = os.path.join(config_dir, self.filename) # 检查配置文件是否存在 if not os.path.exists(config_path): raise FileNotFoundError(f"配置文件 {config_path} 未找到") with open(config_path, 'r', encoding="utf-8") as f: self.config = yaml.safe_load(f) return self.config def get(self, key): """ 传入键返回值,如果有格式嵌套用 . 拼凑 如: app_id = config.get("bot.app_id") """ keys = key.split(".") if len(keys) == 1: return self.config.get(keys[0]) conf = self.config for k in keys: conf = conf.get(k) return conf config = Config() if __name__ == "__main__": config = Config() print(config.get("bot.app_id"))