如何配置文件为相同的键保留多个值? [英] How to ConfigParse a file keeping multiple values for identical keys?

查看:72
本文介绍了如何配置文件为相同的键保留多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够使用 ConfigParser 来读取同一个键的多个值.示例配置文件:

I need to be able to use the ConfigParser to read multiple values for the same key. Example config file:

[test]
foo = value1
foo = value2
xxx = yyy

ConfigParser 的标准"使用中,将有一个键foo,其值为value2.但我需要解析器读取这两个值.

With the 'standard' use of ConfigParser there will be one key foo with the value value2. But I need the parser to read in both values.

按照我创建的输入重复键以下示例代码:

Following an entry on duplicate key I have created the following example code:

from collections import OrderedDict
from ConfigParser import RawConfigParser

class OrderedMultisetDict(OrderedDict):
    def __setitem__(self, key, value):

        try:
            item = self.__getitem__(key)
        except KeyError:
            super(OrderedMultisetDict, self).__setitem__(key, value)
            return

        print "item: ", item, value
        if isinstance(value, list):
            item.extend(value)
        else:
            item.append(value)
        super(OrderedMultisetDict, self).__setitem__(key, item)


config = RawConfigParser(dict_type = OrderedDict)
config.read(["test.cfg"])
print config.get("test",  "foo")
print config.get("test",  "xxx")

config2 = RawConfigParser(dict_type = OrderedMultisetDict)
config2.read(["test.cfg"])
print config2.get("test",  "foo")
print config.get("test",  "xxx")

第一部分(带有config)读取我们通常"的配置文件,只留下value2 作为foo 的值(覆盖/删除另一个值),我得到以下预期输出:

The first part (with config) reads in the config file us 'usual', leaving only value2 as the value for foo (overwriting/deleting the other value) and I get the following, expected output:

value2
yyy

第二部分 (config2) 使用我的方法将多个值附加到列表中,但输出是

The second part (config2) uses my approach to append multiple values to a list, but the output instead is

['value1', 'value2', 'value1\nvalue2']
['yyy', 'yyy']

如何去除重复值?我期待输出如下:

How do I get rid of the repetitive values? I am expecting an output as follows:

['value1', 'value2']
yyy

['value1', 'value2']
['yyy']

(我不介意每个值是否都在列表中......).欢迎任何建议.

(I don't mind if EVERY value is in a list...). Any suggestions welcome.

推荐答案

经过小小的修改,我能够实现你想要的:

After a small modification, I was able to achieve what you want:

class MultiOrderedDict(OrderedDict):
    def __setitem__(self, key, value):
        if isinstance(value, list) and key in self:
            self[key].extend(value)
        else:
            super(MultiOrderedDict, self).__setitem__(key, value)
            # super().__setitem__(key, value) in Python 3

config = ConfigParser.RawConfigParser(dict_type=MultiOrderedDict)
config.read(['a.txt'])
print config.get("test",  "foo")
print config.get("test",  "xxx")

输出:

['value1', 'value2']
['yyy']

这篇关于如何配置文件为相同的键保留多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆