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

问题描述 投票:0回答:1

我有两个文件:

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,但它不包括部分名称,只包括配置,我需要移动所有配置(部分名称和它的配置)。

我只需要一些工作,然后我会看到我可以做什么来插入我的代码。我当然已经阅读了文档,但是我找不到任何粘贴完整部分的内容。

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

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')
python-2.7 file python-2.x configparser
1个回答
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中包装函数的函数,这些函数将帮助完成你在这些api部分add_section & setremove_section & remove_option中尝试找到的函数。

要使用它,您可以创建实例并使用以下内容调用它:

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通常会显示您可以发生的错误,但尝试/除了处理该异常类型。除非我在复制粘贴中犯了错误,否则我最终会把一些我能够测试它的东西放在一起。我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.