配置文件读取ini
config_handler.py
from configparser import ConfigParser class configHandler(ConfigParser): def __init__(self,file,encoding='utf-8'): """ :file:配置文件路径 """ super().__init__()#初始化ConfigParser,config = ConfigParser() self.read(file,encoding=encoding) if __name__ == '__main__': #读取 config = configHandler('py.ini') a = config.get('teachers','name') print(a)
py.ini
[teachers] name = ['zc','zc1']
封装读取ini文件
#!/usr/bin/env python # -*- coding:utf-8 -*- import configparser class readConfig: def __init__(self,filepath): self.filepath = filepath self.config = configparser.ConfigParser() self.config.read(self.filepath) def read_option(self,section,name): value = self.config.get(section,name) return value def read_sections(self): section_list = self.config.sections() return section_list def read_items(self,section): items_list = self.config.items(section) return items_list class writeConfig: def __init__(self,filepath): self.filepath = filepath self.config = configparser.ConfigParser() self.config.read(self.filepath) self.fp = open(self.filepath,'w') def set_option(self,section,name,value): self.config.set(section,name,value) def add_section(self,section): self.config.add_section(section) def add_option(self,section,option,value): self.config.set(section,option,value) def write(self): #修改配置文件结束后都需要调用改方法写入到配置文件 self.config.write(self.fp) if __name__ == '__main__': rc = readConfig(r"C:UsersLLTDesktop est_demopy.ini") host = rc.read_option('DATABASE', 'host') items = rc.config.items('DATABASE') print(items) print(host) # wc = writeConfig(r"D:GitHubconfig.ini") # wc.add_section('info') # wc.add_option('info','name','xiaobialong') # wc.set_option('info','name','xiaobialong2') # wc.write()
读取,修改,yaml文件
#!/usr/bin/env python # -*- coding:utf-8 -*- import yaml class Getyaml(): def __init__(self,path,param=None,message=None): self.path = path # 文件路径 self.param = param # 读取信息的key,不传默认获取所有数据 self.message = message #需要写入的参数 #读取yaml中的数据 def get_data(self): with open(self.path,'rb') as f: c = yaml.load(f.read(),Loader = yaml.FullLoader) # 获取yaml文件中的所有数据,禁用报警,转换格式 if self.param == None: return c # 返回所有数据 else: return c.get(self.param) # 获取键为param的值 # 写入yaml文件 def echo_data(self): with open(self.path,mode='a+',encoding='utf-8') as f: yaml.dump(self.message,stream=f,allow_unicode=True) #传入数据,中文要加allow_unicode=True if __name__ == '__main__': r = r'C:UsersLLTDesktop est_demopy24.yaml' print(Getyaml(path=r,param='demo').get_data()) m = {"key1": "value1", "key2": "value2", "dict_1": {"dict_2": {"dict_3": ["test1", "test2", "test3"]}}} Getyaml(path=r,message=m).echo_data()
py24.yaml
dict_1: dict_2: dict_3: - test1 - test2 - test3 key1: value1 key2: value2