问题描述
我想将Python中的配置文件完全读入数据结构,而无需明确地获取每个值。这样做的原因是我打算以编程方式修改这些值(例如,我有一个变量,说我想将 [Foo] Bar = 1
修改为是 [Foo] Bar = 2
),目的是根据我的更改编写新的配置文件。
I would like to read a configuration file in Python completely into a data structure without explicitly 'getting' each value. The reason for doing so is that I intend to modify these values programatically (for instance, I'll have a variable that says I want to modify [Foo] Bar = 1
to be [Foo] Bar = 2
), with the intention of writing a new configuration file based on my changes.
目前,我正在手工读取所有值:
At present, I'm reading all the values by hand:
parser = SafeConfigParser()
parser.read(cfgFile)
foo_bar1 = int(parser.get('Foo', 'Bar1'))
foo_bar2 = int(parser.get('Foo', 'Bar2'))
我很想拥有(在Google方面找不到很多)是一种将它们读入列表的方法,可以很容易地识别它们,以便我可以将该值从列表中拉出并更改它。
What I would love to have (didn't find much Google-wise) is a method to read them into a list, have them be identified easily so that I can pull that value out of the list and change it.
本质上将其引用为(或类似):
Essentially referencing it as (or similarly to):
config_values = parser.read(cfgFile)
foo_bar1 = config_values('Foo.bar1')
推荐答案
import sys
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.readfp(sys.stdin)
config = dict((section, dict((option, parser.get(section, option))
for option in parser.options(section)))
for section in parser.sections())
print config
输入
Input
[a]
b = 1
c = 2
[d]
e = 3
Output
{'a': {'c': '2', 'b': '1'}, 'd': {'e': '3'}}
这篇关于在Python中自动读取配置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!