1、创建ini文件
2、认识configparse类中基础方法
cfg_obj = configparser.ConfigParser() #创建对象
cfg_obj.read(conf_file_path) #读取配置文件
sections = cfg_obj.sections()#获取配置文件中所有的section节点
options = cfg_obj.options("default")#获取对应节点下的所有key
for sec in sections:
print(cfg_obj.options(sec))
#可使用for循环获取ini文件中各个节点下的key值
value = cfg_obj.get("default","path") #获取对应的value
cfg_obj.set("default","path111","value1111") #设置key和value到ini文件
cfg_obj.add_section("default") #增加section到文件
cfg_obj.remove_section("default") #移除section节点数据
cfg_obj.remove_option("default","patha") #移除节点下的option
config_file_obj = open( conf_file_path,"w") #创建ini文件对象
cfg_obj.write(config_file_obj) #写入文件
judge_value_is_exist = cfg_obj.has_section("default") #判断section节点是否存在
judge_value_is_exist2 = cfg_obj.has_option("default","path")#判断节点下的key是否存在
3、封装,创建一个读取ini文件的工具类
1)创建初始化函数
class ConfigUtils:
def __init__(self,config_file_path):
self.cfg_path = config_file_path
self.cfg =configparser.ConfigParser()
self.cfg.read(self.cfg_path)
2)创建读取配置文件值的方法
def read_value(self,section,key):
value = self.cfg.get(section,key)
return value
3)创建写入配置文件的方法
def write_value(self,section,key,value):
self.cfg.set( section,key,value )
config_file_obj = open( self.cfg_path , "w")
self.cfg.write(config_file_obj)
config_file_obj.flush()
config_file_obj.close()
cfg_obj.set("default","path111","value1111")
原文:https://www.cnblogs.com/dadadaxin/p/14974772.html