从配置文件中排除默认值

问题描述 投票:0回答:1

我正在尝试使用python从config.ini文件中导入CONFIG详细信息。我能够将所有详细信息输入字典。但是,字典也包含[DEFAULT]值。如何从插入字典中排除默认配置。

Python代码:

config = configparser.ConfigParser()
config.read("C:/config.ini")

dictionary = {}
for section in config.sections():
    dictionary[section] = {}
    for option in config.options(section):
            print(section, option, config.get(section, option))
            dictionary[section][option] = config.get(section, option)

配置文件:需要从插入中排除CONCEPT_REFERENCESCHEME

[DEFAULT]
CONCEPT_REFERENCE = http://www.xbrl.org/2003/arcrole/concept-reference
SCHEME = http://xbrl.org/entity/identification/scheme

[SQL]
SERVER_NAME = USER\MSSQLSERVER01
DATABASE = MYDB

[NAME]
path_to_log_file = C:/logs/
path_to_output_files = C:/Map/
python configuration
1个回答
0
投票

[C0的帮助下

answer

如果您想在字典中包含import configparser from configparser import NoSectionError from pprint import pprint class ConfigParser(configparser.ConfigParser): """Can get options() without defaults """ def options(self, section, no_defaults=False, **kwargs): if no_defaults: try: return list(self._sections[section].keys()) except KeyError: raise NoSectionError(section) else: return super().options(section, **kwargs) config = ConfigParser() config.read("test.ini") dictionary = {} for section in config.sections(): dictionary[section] = {} for option in config.options(section,no_defaults=True): dictionary[section][option] = config.get(section, option) >>> {'NAME': {'path_to_log_file': 'C:/Arelle-master/arelle/plugin/ferc/data_migration/logs/', 'path_to_output_files': 'C:/Arelle-master/arelle/plugin/ferc/data_migration/DATA_Map/'}, 'SQL': {'database': 'MYDB', 'server_name': 'USER\\MSSQLSERVER01'}} 部分属性,只是不要在循环中传递[DEFAULT]

no_default=True
© www.soinside.com 2019 - 2024. All rights reserved.