如何使用python3configparser读取具有多个键的配置文件?

2024-09-30 08:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个配置文件,它有多个同名的键。你知道吗

[parentnode]
    parentname = Name of parent
    child = Name of first child
    child = Name of second child
    child = Name of third child
    child = Name of fourth child

我需要能够读取此文件,进行修改,并将其写入其他文件。我试着看看我是否可以读取配置文件并在不做任何更改的情况下正确地编写它。你知道吗

import configparser
from collections import OrderedDict

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)


configParser = configparser.ConfigParser(defaults=None, dict_type=MultiOrderedDict, strict=False)
configParser.read('test.config')
with open('output.config', 'w') as configfile:
    configParser.write(configfile)

但是,在outputfile中,我得到了以下内容,没有child键。如何确保使用configparser.write()编写的输出文件与输入文件相同?你知道吗

[parentnode]
parentname = Name of parent
child = Name of first child
    Name of second child
    Name of third child
    Name of fourth child

Tags: 文件ofkeynameselfchildvalue配置文件

热门问题