【问题标题】:Getting value out of ConfigParser instead of string从 ConfigParser 而不是字符串中获取价值
【发布时间】:2017-08-26 02:14:50
【问题描述】:

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

【问题讨论】:

  • 您可以继承 ConfigParser 并覆盖 _read 方法以及更新 RawParser.OPTCRE 正则表达式(用于解析选项行)。但最简单和最可靠的方法可能是在您的代码中使用.split(',')
  • 将 .split(',') 添加到 param[1] 有效!如果您想回答这个问题,我会将其标记为已接受。

标签: python parsing dictionary config ini


【解决方案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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多