2017-03-31 77 views
0

我有一个file.ini结构类似这样:获得价值了ConfigParser的,而不是字符串

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

+0

您可以继承'ConfigParser'并覆盖'_read'方法以及更新'RawParser.OPTCRE'正则表达式(用于解析选项行)。但最简单和最可靠的方法可能就是在代码中执行'.split(',')'。 – FamousJameous

+0

添加.split(',')param [1]工作!如果您想回答这个问题,我会将其标记为已接受。 – Acoustic77

回答

1

您可以在解析的数据上使用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 

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

相关问题