Python configparser模組常用方法解析
ConfigParser模組在python中用來讀取配置檔案,配置檔案的格式跟windows下的ini配置檔案相似,可以包含一個或多個節(section),每個節可以有多個引數(鍵=值)。使用的配置檔案的好處就是不用在程式設計師寫死,可以使程式更靈活。
注意:在python 3 中ConfigParser模組名已更名為configparser
configparser函式常用方法:
讀取配置檔案:
read(filename) #讀取配置檔案,直接讀取ini檔案內容
sections() #獲取ini檔案內所有的section,以列表形式返回['logging','mysql']
options(sections) #獲取指定sections下所有options ,以列表形式返回['host','port','user','password']
items(sections) #獲取指定section下所有的鍵值對,[('host','127.0.0.1'),('port','3306'),('user','root'),('password','123456')]
get(section,option) #獲取section中option的值,返回為string型別
>>>>>獲取指定的section下的option <class 'str'> 127.0.0.1getint(section,option) 返回int型別
getfloat(section,option) 返回float型別
getboolean(section,option) 返回boolen型別
舉例如下:
配置檔案ini如下:
[logging]
level = 20
path =
server =[mysql]
host=127.0.0.1
port=3306
user=root
password=123456
注意,也可以使用:替換=
程式碼如下:
import configparser from until.file_system import get_init_path conf = configparser.ConfigParser() file_path = get_init_path() print('file_path :',file_path) conf.read(file_path) sections = conf.sections() print('獲取配置檔案所有的section',sections) options = conf.options('mysql') print('獲取指定section下所有option',options) items = conf.items('mysql') print('獲取指定section下所有的鍵值對',items) value = conf.get('mysql','host') print('獲取指定的section下的option',type(value),value)
執行結果如下:
file_path : /Users/xxx/Desktop/xxx/xxx/xxx.ini
獲取配置檔案所有的section ['logging','mysql']
獲取指定section下所有option ['host','password']
獲取指定section下所有的鍵值對 [('host','123456')]
獲取指定的section下的option <class 'str'> 127.0.0.1
綜合使用方法:
import configparser """ 讀取配置檔案資訊 """ class ConfigParser(): config_dic = {} @classmethod def get_config(cls,sector,item): value = None try: value = cls.config_dic[sector][item] except KeyError: cf = configparser.ConfigParser() cf.read('settings.ini',encoding='utf8') #注意setting.ini配置檔案的路徑 value = cf.get(sector,item) cls.config_dic = value finally: return value if __name__ == '__main__': con = ConfigParser() res = con.get_config('logging','level') print(res)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。