2013-05-30 40 views
0

我希望能夠從配置文件部分讀取文件的變量列表,並使用該列表中的鍵指向定義每個文件屬性的更多部分。這些文件可以在數量,名稱和屬性上有所變化。有沒有人看到過這樣做的方法,或者可以指向正確的方向?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 
+0

到底是什麼問題,需要做什麼? –

+0

好問題...我認爲是分析了這一點。我想我可以在[路徑]部分中獲取密鑰列表。有時候確實很簡單... – BillR

回答

0

有標準模塊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() 


+0

注意:這個例子是基於Python 3的;它不適用於2.x –