简体   繁体   中英

Unknown quantity of items in configuration files using ConfigParser

To be honest I'm writing this question to try to clear up my mind in the process. If I can't figure it out, I'll post it (which happened). I would appreciate if someone could shed some light on how to approach this problem. I'm still noob enough to get overwhelmed by this kind of problems.

Let's say that in certain section of my config file I want to give the user the flexibility to add an arbitrary quantity of items, eg:

[mysection]
item1 = value1
item2 = value2
item3 = value3

The items quantity can increase as the user wishes.

Which would be a nice way to parse this? At the moment I only came up with string manipulation by index of the list returned by ConfigParser's items method.

Hope I explained myself clear. Anyone has faced this before?

If I understand your question correctly, it seems to me that ConfigParser.items(section) offers the functionality you need.


Perhaps it would help to know that you can call dict on the resulting list of tuples? As in...

>>> l = [('name1', 'val1'), ('name2', 'val2')]
>>> d = dict(l)
>>> d
{'name2': 'val2', 'name1': 'val1'}
>>> d.items()
[('name2', 'val2'), ('name1', 'val1')]
>>> d.keys()
['name2', 'name1']
>>> d.values()
['val2', 'val1']

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