python configparser将section节值映射到其他节

时间:2013-05-30 17:17:06

标签: python configparser

我希望能够从配置文件部分读取变量文件列表,并使用该列表中的键指向定义每个文件属性的更多部分。文件可以更改数量,名称和属性。有没有人见过这样做的方法,或者能指出我正确的方向?

[paths]
file1=/some/path/
file2=/some/other/path

[file1]
key_specific_to_file_1=some_attribute_value

[file2]
key_specific_to_file_2=some_attribute_value2

[non-file-related-section]
some_key=some-other-value

1 个答案:

答案 0 :(得分:0)

有标准模块配置程序。文档可以找到configparser documentation

简单的例子:



    #/usr/bin/env python
    import configparser
    import sys

    def config_reader(filename):
        try:
            config = configparser.ConfigParser()
            config.read(filename )
            section_list = config.sections()
            for section_name in section_list:
                for key in config[section_name]:
                    print("Key : " +  config[section_name ][key])
        except configparser.Error as e:
            print(e)
            return 

    def main():
        print("config file " + sys.argv[1])
        config_reader(sys.argv[1])


    if __name__ == "__main__":
        main()


相关问题