我有一個如下所示的配置文件,其中包含一個列表。[my_variables]dict = [{'name': 'Jack', 'age': 26}, {'name': 'Ray', 'age': 34}, {'name': 'Aby', 'age': 18}]我正在嘗試使用 ConfigParser 讀取此列表。但是,它被讀取為一個字符串。我怎樣才能按原樣將其作為列表閱讀。>>> import ConfigParser, os>>> config = ConfigParser.ConfigParser()>>> config.readfp(open('myConfig.properties'))>>> a = config.get('my_variables', 'dict')>>> a"[{'name': 'Jack', 'age': 26}, {'name': 'Ray', 'age': 34}, {'name': 'Aby', 'age': 18}]">>> type(a)<type 'str'>預期結果: a 應該是所提到的列表。請提出任何方法來做到這一點。謝謝....
1 回答

慕無忌1623718
TA貢獻1744條經驗 獲得超4個贊
這奏效了...
import ConfigParser, os
config = ConfigParser.ConfigParser()
config.readfp(open('myConfig.properties'))
a = config.get('my_variables', 'dict')
b = ast.literal_eval(a)
b
[{'age': 26, 'name': 'Jack'}, {'age': 34, 'name': 'Ray'}, {'age': 18, 'name': 'Aby'}]
type(b)
<type 'list'>
添加回答
舉報
0/150
提交
取消