1

I am using ConfigObj in Python to read from my config file. I need to read a list of lists from the config file. Here's what I've tried so far:

  1. sections and subsections - creates dictionaries, not lists
  2. list_of_lists = (1, 2, (3, 4)) - ConfigObj treats everything as strings, and produces the list ['(1', '2', '(3', '4))']

What I would like to have (in Python context) is something like this: list_of_lists = [1, 2, [3, 4, ]]

Can someone please suggest a way to do this? I'm open to alternatives as well. Thanks in advance.

th3an0maly
  • 3,360
  • 8
  • 33
  • 54
  • Can you provide an example of the key you would like to use and the value would like for it to have? – aquil.abdullah Apr 12 '17 at 13:38
  • @aquil.abdullah Sure. I've added that to the question – th3an0maly Apr 12 '17 at 13:44
  • 1
    I've rescinded my answer as it doesn't seem to answer your question. What I did find was that __Values are always strings - if you want integers, or anything else, you can do the conversion yourself__. So it is up to you to deserialize any objects that aren't meant to be strings. – aquil.abdullah Apr 12 '17 at 14:26
  • @aquil.abdullah there is int_list, float_list, etc. check https://configobj.readthedocs.io/en/latest/validate.html – pianissimo Feb 25 '19 at 19:14

3 Answers3

1

Here is an alternate approach using configparaser

# Contents of configfile
[section1]
foo=bar
baz=oof
list=[1,2,[3,4,]]

Code to get list of lists:

import configparser
import ast
cfg = configparser.ConfigParser()
cfg.read_file(open('configfile'))
s1 = cfg['section1']
list_of_lists = ast.literal_eval(s1.get('list')
print list_of_lists

# output
# [1, 2, [3, 4]]
aquil.abdullah
  • 3,059
  • 3
  • 21
  • 40
0

I just solved it by this way using configobj

ini: config/test.ini

[List]
AA = aa,bb
BB = cc,dd

python: main.py

# Read a config file
from configobj import ConfigObj
config = ConfigObj('.\config\test.ini')

print(config['List'])
print(config['List']['AA'])
print(config['List']['BB'])
W Kenny
  • 1,855
  • 22
  • 33
-1

Try this,

# Read a config file
from configobj import ConfigObj
config = ConfigObj(filename)

# Access members of your config file as a dictionary. Subsections will also be dictionaries.

value1 = config['keyword1']
value2 = config['section1']['keyword3']

Refer to ConfigObj Documentation.

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
  • Like I specified in the question, I need a list of lists, not a dictionary – th3an0maly Apr 13 '17 at 13:10
  • @th3an0maly, convert a dict into a list of lists by `lists = [[v, k] for k, v in d.iteritems()]`. Does it work for you? – SparkAndShine Apr 13 '17 at 14:20
  • Yes and no. Yes, because it can be used as a workaround along with some parsing. No because I was looking for a config reader that would provide this out of the box. Thank you. – th3an0maly Apr 14 '17 at 09:53