简体   繁体   中英

Reading a configuration file in Python (storing/reading nested data with ConfigParser)

I am writing a list processing script that needs to read configuration data about each item in the list. The configuration data is best represented as a nested tree.

I would normally have used YAML for storing the data - but I think that using ConfigParser would be a more Pythonic approach - and make the script more 'transparent' to other Python coders - since a surprising number of people are not familiar with the YAML format.

I have had a very quick look at the configParser documentation , but I have not been able to ascertain whether it can deal with nested data.

My configuration data will have the following structure:

<markers>
    <marker>
        <date></date>
        <value></value>
    </marker>
</markers>
<items>
    <item>
        <start></start>
        <end></end>
        <mcc>
           <chg>
                <date></date>
                <ival></ival>
                <fval></fval>
           </chg>
        </mcc>
    </item>
</items>

Can I use ConfigParser to read/(write ?) this kind of nested data in a config file? (I'm more interested in being able to read than writing the config file. I don't mind manually writing the config file if necessary).

No, configparser doesn't support nesting. You could look at configObj instead. It's mature and quite widely used.

As per your xml data you need section and subsection. So you can use the ConfigParser but you have to give sub section with some meaning like

[markers]
[markers.marker]
date=''
value=''

[items]
[items.item]
start=''
end=''
[items.item.mcc]
[items.item.mcc.chg]
date=''
ival=''
fval=''

Then you have to override the getsection function to get the nested data.

TOML configuration files follow a similar syntax to INI files and allow for nested structures. See the official specification here and the corresponding python library here .

Example:

>>> import toml
>>> toml_string = """
... # This is a TOML document.
...
... title = "TOML Example"
...
... [owner]
... name = "Tom Preston-Werner"
... dob = 1979-05-27T07:32:00-08:00 # First class dates
...
... [database]
... server = "192.168.1.1"
... ports = [ 8001, 8001, 8002 ]
... connection_max = 5000
... enabled = true
...
... [servers]
...
...   # Indentation (tabs and/or spaces) is allowed but not required
...   [servers.alpha]
...   ip = "10.0.0.1"
...   dc = "eqdc10"
...
...   [servers.beta]
...   ip = "10.0.0.2"
...   dc = "eqdc10"
...
... [clients]
... data = [ ["gamma", "delta"], [1, 2] ]
...
... # Line breaks are OK when inside arrays
... hosts = [
...   "alpha",
...   "omega"
... ]
... """
>>> parsed_toml = toml.loads(toml_string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM