python configparser将节值映射到其他节

2024-04-20 11:08:11 发布

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

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

[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

Tags: 文件topathkey列表属性value配置文件
1条回答
网友
1楼 · 发布于 2024-04-20 11:08:11

有标准模块configparser。可以找到文档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()


相关问题 更多 >