I have a file.ini structured like so:
item1 = a,b,c
item2 = x,y,z,e
item3 = w
and my configParser is set like this:
def configMy(filename='file.ini', section='top'):
parser = ConfigParser()
parser.read(filename)
mydict = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
mydict[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return mydict
right now "mydict" is returning key-value pairs of strings, ie: {'item1': 'a,b,c', 'item2': 'x,y,e,z', 'item3':'w'}
how can I alter it to return the value as a list? like this: {'item1': [a,b,c], 'item2': [x,y,e,z], 'item3':[w]}
You can use split
on the parsed data to split the list.
def configMy(filename='file.ini', section='top'):
parser = ConfigParser()
parser.read(filename)
mydict = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
mydict[param[0]] = param[1].split(',')
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return mydict
If needed, you could then add some more logic to convert back to a single value if the list only has a single value. Or check for commas in the value before splitting.
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.