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'))
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
{'a': {'c': '2', 'b': '1'}, 'd': {'e': '3'}}