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

Python 从ConfigParser中获取值而不是字符串,python,parsing,dictionary,config,ini,Python,Parsing,Dictionary,Config,Ini,我有一个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

我有一个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”正在返回字符串的键值对,即:
{'item1':'a,b,c','item2':'x,y,e,z','item3':'w'}

如何更改它以列表形式返回值?这样地:
{'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

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

您可以将
ConfigParser
子类化,覆盖
\u read
方法,并更新
RawParser.OPTCRE
regex(用于解析选项行)。但最简单、最可靠的方法可能是在代码中执行
.split(',')
。将.split(',')添加到param[1]中很有效!如果你愿意回答这个问题,我会把它标记为接受。