2016-10-24 26 views
0

我從S3存儲桶中提取配置文件。它的內容以String形式返回。我的目標是將這個配置內容字符串轉換爲字典。 這裏是在配置文件中的內容的樣子:如果可能的話,將配置文件的內容轉換爲字典

[Credentials] 
user=user123 
pw=pass123 

[Tables] 
table=1 
table=2 
+0

你嘗試ConfigParser,https://docs.python.org/2/library/configparser.html? – Samundra

+0

我沒有。配置文件的內容作爲字符串返回。我沒有看到configparser在這裏可以提供什麼幫助。 – NewToAppium

+0

這個庫可以幫助:https://github.com/pylover/pymlconf – pylover

回答

0

您可以使用ConfigParser

from configparser import ConfigParser 
config_parser = ConfigParser() 
config_parser.read_string(your_config_as_string) 
user = config_parser.get('Credentials', 'user') 

這裏,user值是現在user123如果your_config_as_string如下是:

[Credentials] 
user=user123 
pw=pass123 

如果你想在config_parser的內容轉換爲一個字典,你可以在sectionsoptions迭代config_parser

config = { 
    section: { 
     option: config_parser.get(section, option) 
     for option in config_parser.options(section) 
    } for section in config_parser.sections() 
} 

這將導致一個字典爲: {'Credentials': {'pw': 'pass123', 'user': 'user123'}}

相關問題