我想知道是否有一种方法可以使用 Python 的 ConfigParser 处理动态配置文件。所谓动态,是指配置文件的结构不固定。
例如,我可以有下面的配置文件。
[SectionA]
FieldA1 = stringA1
FieldA2 = stringA2
FieldA3 = stringA3
[SectionB]
FieldB1 = stringB1
FieldB2 = stringB2
FieldB3 = stringB3
我还可以有下面的配置文件(一个额外的字段值添加到部分 B)。
[SectionA]
FieldA1 = stringA1
FieldA2 = stringA2
FieldA3 = stringA3
[SectionB]
FieldB1 = stringB1
FieldB2 = stringB2
FieldB3 = stringB3
FieldB4 = stringB4
应该使用相同的代码来解析两个配置文件。到目前为止,我只看到了字段是硬编码的示例,例如给定的示例 here ,这需要事先了解每个部分的字段。
import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
... 'Compression': 'yes',
... 'CompressionLevel': '9'}
有没有办法动态读取每个部分中的字段/值?
最佳答案
来自 pymotw.com
from configparser import SafeConfigParser
parser = SafeConfigParser()
parser.read('config.ini')
for section_name in parser.sections():
print ('Section:', section_name)
print (' Options:', parser.options(section_name))
for name, value in parser.items(section_name):
print(name, value)
print()
因为我看到你使用 configparser
,所以我刚刚针对 python3 做了一个改编。享受吧!
关于python - 动态配置解析器(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37722657/