Python - configparser模組:用於配置檔案
阿新 • • 發佈:2022-03-31
支援多種格式的配置檔案,如ini,yaml,xml....
ini是按需讀取,yaml是一次性讀取
這裡以.ini為例
ini配置檔案格式
格式 [section] option=value option=value [section] option=value option=value option=value 示例 [database] user=sa password=123abc [log] name=log_name level=INFO
學習筆記:讀取、新增、修改、儲存
1 from configparser import ConfigParser 2 3# 1. 例項化 4 conf = ConfigParser() 5 6 # 2. 讀取配置檔案:read() 7 conf.read('config.ini', encoding='utf-8') # 注意配置檔案的路徑 8 9 # 3. 讀取某一項配置:get() 10 value = conf.get('log', 'file_ok') 11 print(type(value)) # <class 'str'> 12 value = conf.getboolean('log', 'file_ok') 13 print(type(value)) #<class 'bool'> 14 value = conf.get('log', 'size') 15 print(type(value)) # <class 'str'> 16 value = conf.getint('log', 'size') 17 print(type(value)) # <class 'int'> 18 19 # 4.1 讀取配置檔案所有sections 20 print(conf.sections()) # ['database', 'log'] 21 # 4.2 讀取配置檔案指定section的所有options22 print(conf.options('log')) # ['name', 'level', 'file_ok', 'size'] 23 24 # 5.1 新增section 25 conf.add_section('section') 26 # 5.2 存在option,重寫value;不存在,則新增 27 conf.set('section', 'name', 'new_value') 28 29 # 6. 修改配置項:寫入記憶體set() 30 conf.set('log', 'name', 'new_value') # 只改變記憶體,不改變檔案 31 32 # 7. 儲存到檔案 write() 33 conf.write(open('config.ini', 'w', encoding='utf-8')) # 執行此行就是把上面的修改重寫到原來的配置檔案中
封裝
1 import os 2 from configparser import ConfigParser 3 4 class HandleConfig(ConfigParser): 5 6 def __init__(self, file_path): 7 super().__init__() 8 self.read(file_path, encoding='utf-8') 9 10 file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini') 11 conf = HandleConfig(file_path)
呼叫
myConfig是HandleConfig()類的檔名,直接引入類的例項化,就不需要每次呼叫都例項化一次了
1 from myConfig import conf 2 3 print(conf.get('log', 'level')) # INFO