从 ConfigParser 而不是字符串中获取值

Getting value out of ConfigParser instead of string

我有一个 file.ini 结构如下:

item1 = a,b,c
item2 = x,y,z,e
item3 = w

我的 configParser 设置如下:

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

现在 "mydict" 正在 returning 键值对字符串,即: {'item1': 'a,b,c', 'item2': 'x,y,e,z', 'item3':'w'}

如何将其更改为 return 作为列表的值?像这样: {'item1': [a,b,c], 'item2': [x,y,e,z], 'item3':[w]}

您可以对解析后的数据使用split来拆分列表。

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

如果需要,如果列表只有一个值,您可以添加更多逻辑以转换回单个值。或者在拆分前检查值中的逗号。