python-通過configparser模組讀取字尾為 .ini 的配置檔案資訊
阿新 • • 發佈:2020-08-04
前言
一般為了方便會將路徑,連線資訊等寫到配置檔案(通常會將這些資訊寫到yaml,ini....配置檔案)中,configparser模組讀取字尾為 .ini 的配置檔案資訊
配置檔案格式
#存在 config.ini 配置檔案,內容如下:
[DEFAULT]
excel_path = ../test_cases/case_data.xlsx
log_path = ../logs/test.log
log_level = 1
[email]
user_name = [email protected]
password = 123456
讀取配置檔案的基本語法
import configparser #建立配置檔案物件 conf = configparser.ConfigParser() #讀取配置檔案 conf.read('config.ini', encoding="utf-8") #列表方式返回配置檔案所有的section print( conf.sections() ) #結果:['default', 'email'] #列表方式返回配置檔案email 這個section下的所有鍵名稱 print( conf.options('email') ) #結果:['user_name', 'password'] #以[(),()]格式返回 email 這個section下的所有鍵值對 print( conf.items('email') ) #結果:[('user_name', '[email protected]'), ('password', '123456')] #使用get方法獲取配置檔案具體的值,get方法:引數1-->section(節) 引數2-->key(鍵名) value = conf.get('default', 'excel_path') print(value)
專案實踐