Search code examples
pythonstringlistconfigparser

How to set a list (not a string) on a configparser parameter


I want to set a parameter of an .ini file. I use the configparser module, but I notice that every time I save a parameter, it is stored as a string. It there a possibility to convert a string formatted as a list, like "['p1', 'p2', 'p3']", into a list?

This is what I do:

list1 = ['ALL'] # initial list value

tmpList = cfg.get('DEFAULT', 'list1')
for i in range(0, len(tmpList)):
    list1.insert(tk.END, tmpList[i])

He returns, with a print:

[
'
A
L
L
'
]

Solution

  • You can convert python valid string object to actaul by using of ast.literal_eval

    import ast
    l1 = "['p1', 'p2', 'p3']"
    l2 = ast.literal_eval(l1)
    >>> l2
    >>> ['p1', 'p2', 'p3']
    >>> type(l2)
    >>> <class 'list'>