Reading a configuration file in Python (storing/reading nested data with ConfigParser)
-
29-04-2021 - |
문제
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.