使用configparser将部分从一个配置文件移动到另一个

时间:2019-03-08 14:20:25

标签: python-2.7 file python-2.x configparser

我有两个文件:

test1.conf:

[1414]
musicclass = cowo1108
eventwhencalled = yes
eventmemberstatus = yes
membermacro = AnswerNotifyOngoingEntered
strategy = ringall
timeout = 35

test2.conf:

[1415]
musicclass = cowo1108
eventwhencalled = yes
eventmemberstatus = yes
membermacro = AnswerNotifyOngoingEntered
strategy = ringall
timeout = 35

我只想将test1.conf中的[1414]部分放在test2.conf中的部分之下,然后从test1.conf中删除

我尝试将部分转换为字典,然后将其添加到test2中,但是它不包括部分名称,仅包含配置,并且我需要移动所有配置(部分名称及其配置)。 / p>

我只需要处理一些事情,然后我将看到如何在代码中插入它。我当然已经阅读了文档,但是找不到任何内容可以粘贴整个章节。

这是我尝试过的(文件很大,所以我得到了一部分):

config = configparser.ConfigParser(strict=False,comment_prefixes='/',allow_no_value=True)
with open('test1.conf', "r") as f:
    config.readfp(f)

for general_queue_id in config.sections():
    general_id_arr.append(general_queue_id)

for key in general_id_arr: # Array with all sections from test1.conf
    with open('teste2.conf'):
        items = {k:v for k,v in config.items(key)}
        for x in items.items():
            f.write(x[0] + '=' + x[1] + '\n')

1 个答案:

答案 0 :(得分:0)

如果您已经知道要查找的部分,则可以更轻松地使用configParser中的内置函数,可以将其内置到包装类中。

例如,我使用以下代码创建解析器,然后将一个节中的所有项目作为列表。

from configparser import ConfigParser, ExtendedInterpolation


class MyConfigParser(object):

    def __init__(self):
        """
        initialize the file parser with
        ExtendedInterpolation to use ${Section:variable} format
        [Section]
        option=variable
        """
        self.config_parser = ConfigParser(interpolation=ExtendedInterpolation())

    def read_ini_file(self, file):
        """
        Parses in the passed in INI file.

        :param file: INI file to parse
        :return: INI file is parsed
        """
        with open(file, 'r') as f:
            self.config_parser.read_file(f)

    def add_section_toFile(self, section):
        """
        adds a configuration section to a file

        :param section: configuration section to add in file
        :return: void
        """
        if not self.config_parser.has_section(section):
            self.config_parser.add_section(section)

    def add_configurations_to_section(self, section, lst_config):
        """
        Adds a configuration list to configuration section

        :param section: configuration section
        :param lst_config: key, value list of configurations
        :return: void
        """
        if not self.config_parser.has_section(section):
            self.add_section_toFile(section)

        for option, value in lst_config:
            print(option, value)
            self.config_parser.set(section, option, value)


    def get_config_items_by_section(self, section):
        """
        Retrieves the configurations for a particular section

        :param section: INI file section
        :return: a list of name, value pairs for the options in the section
        """
        return self.config_parser.items(section)

    def remove_config_section(self, section):
        """
        Removes a configuration section from a file
        :param section: configuration section to remove
        :return: void
        """
        self.config_parser.remove_section(section)

    def remove_options_from_section(self, section, lst_options):
        """
        Removes a list of options from configuration section
        :param section: configuration section in file
        :param lst_options: list of options to remove
        :return: void
        """
        for option, value in lst_options:
            self.config_parser.remove_option(section, option)

    def write_file(self, file, delimiter=True):
        with open(file, 'w') as f:
            self.config_parser.write(f, delimiter)


我添加了一些函数,这些函数包装了configParser api中的函数,这些函数将帮助完成您在add_section & setremove_section & remove_option这些api部分中找到的内容

要使用它,您可以创建实例并使用诸如以下的名称进行调用:

from config_parser import MyConfigParser


def main():
    lst_section = []

    fileIn = './test1.conf'
    fileOut = './test2.conf'

    parser1 = MyConfigParser()
    parser2 = MyConfigParser()

    parser1.read_ini_file(fileIn)
    parser2.read_ini_file(fileOut)

    lst_section = parser1.get_config_items_by_section('1414')

    parser2.add_section_toFile('1414')
    parser2.add_configurations_to_section('1414', lst_section)

    parser1.remove_config_section('1414')

    parser1.write_file(fileIn)
    parser2.write_file(fileOut)


if __name__ == "__main__":
    main()

MyConfigParser类是一个快速构建,因此,如果要在生产类型环境中使用它,则将需要添加更强大的错误处理以捕获诸如section选项已经存在的情况。 configParser api通常会显示将发生什么错误,您可以尝试/例外来处理该异常类型。除非我在复制粘贴中弄错了,否则我最终会整理出一些我能够测试的内容,以便为您运行。我希望这有帮助。

相关问题