1. 程式人生 > 其它 >python簡單讀寫ini檔案

python簡單讀寫ini檔案

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")