Python讀寫配置檔案模組--Configobj
阿新 • • 發佈:2021-06-14
from configobj import ConfigObj import os # Python讀寫配置檔案模組--Configobj class TestConfig(): def __init__(self): self.path = os.path.dirname(os.path.dirname(__file__)) + "/config/config.ini" print(self.path) # 例項化一個Configobj物件,給ConfigObj一個配置檔案的路徑,然後通過字典來訪問成員,子段也是一個字典 self.config = ConfigObj(self.path, encoding='UTF-8') # 讀取配置檔案資訊 def query_config(self): print(self.config['HJ']) print(self.config['HJ']['hj']) # 給配置檔案新增新項 def add_config(self): self.config['data'] = {} self.config['data']['user'] = 'root' self.config.write() # 修改配置檔案 def modify_config(self):print(self.config['HJ']['hj']) self.config['HJ']['hj'] = 'regression' self.config.write() print(self.config['HJ']['hj']) self.config['HJ']['hj'] = 'maoyan' self.config.write() print(self.config['HJ']['hj']) # 刪除配置檔案中的某個項 def del_config(self):del self.config['data']['user'] del self.config['data'] self.config.write() # 將配置檔案寫入到不同的檔案 def write_other_file(self): self.config.filename = os.path.dirname(os.path.dirname(__file__)) + "/config/test.ini" self.config.write() # 建立一個新配置檔案 def create_new_config(self): config = ConfigObj() config.filename = os.path.dirname(os.path.dirname(__file__)) + "/config/test1.ini" config['student'] = {} config['student']['name'] = 'Jardon' config['student']['age'] = '56' config.write() if __name__ == '__main__': t = TestConfig() # t.query_config() # t.modify_config() # t.add_config() # t.del_config() # t.write_other_file() t.create_new_config()