consolidator
/
MyConfig.py
36 строк · 1.1 Кб
1import json
2import os.path
3from typing import Any
4
5class MyConfig(object):
6
7def __init__(self,fileName:str,encoding:str="UTF-8"):
8self.fileName=fileName
9self.fileEncoding=encoding
10self.config = {}
11try:
12if not os.path.isfile(fileName): raise Exception(f"Файл {fileName} отсутсвует")
13with open(file=fileName,encoding=encoding,mode="r") as fs:
14self.config = json.load(fs)
15except: raise
16
17def get(self,key:str,defaultValue)->Any:
18return self.config.get(key,defaultValue)
19
20def set(self,key:str,value):
21try:
22self.config.update({key:value})
23except: raise
24
25def get_keys(self)->dict:
26keys={}
27for key in self.config.keys():
28keys[key]=str(type(self.config[key]))
29return keys
30
31def sync(self):
32try:
33with open(self.fileName,encoding=self.fileEncoding,mode="w") as fs:
34json.dump(self.config, fs, indent=2, sort_keys=False, ensure_ascii=False)
35fs.flush()
36except: raise
37