2

I use python ConfigObj to load a config file, it works great if config file in pattern "cfgName=cfgvalue".

Now I need write config file in this way:

basket.ini

[favoFruit]
Apple
Orange

can (how) load this as a list favoFruit['Apple','Orange'] by ConfigObj?

Current I only can get error message Invalid line at line "2" when using cfgObj=ConfigObj('basket.ini')

The YAML or JSON can do this, my question is can ConfigObj do it too?

jcollado
  • 39,419
  • 8
  • 102
  • 133
brike
  • 313
  • 4
  • 10

1 Answers1

3

configobj doesn't support lists the way you're trying to use them, but as comma separated values:

[fruit]
favourite = Apple, Orange

In your code you just have to access the attribute as usual:

>>> cfg = configobj.ConfigObj('basket.ini')
>>> cfg['fruit']['favourite']
['Apple', 'Orange']

For more information, please have a look at this article.

Edit: If you really need to support configuration file with exactly the same format as in your question, note that it would be easy to write a custom parser for it:

import re
from collections import defaultdict

def parse(f):
    data = defaultdict(list)
    section = None
    for line in f:
        line = line.strip()
        if not line:
            continue
        match = re.match('\[(?P<name>.*)\]', line)
        if match:
            section = match.group('name')
        else:
            data[section].append(line)
    return data

cfg = parse(open('basket.ini'))
print cfg['favoFruit']

Example output:

['Apple', 'Orange']

jcollado
  • 39,419
  • 8
  • 102
  • 133