天天看點

Python ConfigParser

ConfigParser

在深度學習中,我打算用這個類來處理參數檔案,xx.ini或者xx.cfg。

一、基本操作

1、基本的讀取配置檔案

  • read(filename) - 直接讀取ini,cfg檔案内容
  • sections() - 得到所有的section,并以清單的形式傳回
  • options(section) - 得到該section的所有option
  • items(section) - 得到該section的所有鍵值對
  • get(section,option) - 得到section中option的值,傳回為string類型
  • getint(section,option) - 得到section中option的值,傳回為int類型,還有相應的getboolean()和getfloat() 函數。

2、基本的寫入配置檔案

  • add_section(section) - 添加一個新的section
  • set( section, option, value) - 對section中的option進行設定,需要調用write将内容寫入配置檔案。

以上可能有些不全,我就記錄了我常用的一些操作,如果有時候還可以getboolean類型的資料。

二、Demo

1、讀取parameter檔案:test.ini

[aaa]
a1 = a1
a2 = 222

[bbb]
b1 = b1
b2 = true           

這個檔案的格式:

節: [session]

參數: 鍵=值 name = value

讀取test.ini

config = ConfigParser()
config.read('test.ini')
for section in config.sections():
    for k, v in config.items(section):
        print(k, v)           

最關鍵的地方是配合@property的使用,就能将配置檔案的所有參數轉換為一個類的所有參數

@property
def aaa_a1(self):
    return self._config.get('aaa', 'a1')           

2、寫入檔案

config.write(open(self.config_file, 'w'))