2017-03-31 65 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 

如果需要,您可以添加更多的邏輯來轉換回單個值,如果列表只有一個值。或者在分割之前檢查值中的逗號。