th3an0maly
th3an0maly

Reputation: 3510

How to create a list of lists in the config, while using ConfigObj in Python?

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.

Upvotes: 1

Views: 1806

Answers (3)

W Kenny
W Kenny

Reputation: 2089

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'])

Upvotes: 0

aquil.abdullah
aquil.abdullah

Reputation: 3157

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]]

Upvotes: 1

SparkAndShine
SparkAndShine

Reputation: 18045

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.

Upvotes: -1

Related Questions