簡體   English   中英

從配置文件中讀取 Python 列表

[英]Read a Python List from a config file

我有一個如下配置文件,其中包含一個列表。

[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 應該是上述列表。

請提出任何方法來做到這一點。

謝謝....

這有效...

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'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM