python提供了configparser庫用於配置文件的讀取。
一般情況下,配置文件格式如下圖所示:
配置文件分為兩個section, section的名字在中括號內[***]。如果想讀取某個section中的配置參數(option),就可以調用config.get(section=section, option=option)。
1 # -*- coding:utf-8 -*- 2 import os 3 import configparser 4 5 # 項目路徑 6 rootDir = os.path.split(os.path.realpath(__file__))[0] 7 # config.ini文件路徑 8 configFilePath = os.path.join(rootDir, 'config.txt') 9 10 11 def get_config_values(section, option): 12 """ 13 根據傳入的section獲取對應的value 14 :param section: ini配置文件中用[]標識的內容 15 :return: 16 """ 17 config = configparser.ConfigParser() 18 config.read(configFilePath) 19 # return config.items(section=section) 20 return config.get(section=section, option=option) 21 22 23 if __name__ == '__main__': 24 result = get_config_values('mysql2', 'port') 25 print(result)
運行結果如下: