【问题标题】:python configparser map section values to other sectionspython configparser 将部分值映射到其他部分
【发布时间】:2013-05-30 17:17:05
【问题描述】:

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

[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

【问题讨论】:

  • 究竟是什么问题,需要做什么?
  • 好问题...我认为分析过度了。我想我可以在 [paths] 部分中获取键列表。有时候真的就是这么简单……

标签: python configparser


【解决方案1】:

有标准模块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()


【讨论】:

  • 注意:本示例基于 Python 3;它不适用于 2.x
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多