[英]How can I read in lists within a list using ConfigParser() in Python?
I have seen a lot of answers on how to read in a list using ConfigParser in Python:我已经看到很多关于如何在 Python 中使用 ConfigParser 读取列表的答案:
But I am wondering how I can read in a list with multiple lists但我想知道如何在包含多个列表的列表中阅读
For example, I have a config.ini :例如,我有一个config.ini :
[INPUT]
values = [[40000, 60000], [70000, 80000]]
A function in my main.py needs to read the above as:我的 main.py 中的function需要将上述内容读取为:
[[40000, 60000], [70000, 80000]]
I am not sure if it matters, but values can be any size list, so for example:我不确定这是否重要,但值可以是任何大小的列表,例如:
[[40000, 60000]]
or或者
[[40000, 60000], [70000, 80000], [90000, 95000]]
I know the below will not work, but for clarity, I am reading the lists within the list into main.py like this:我知道以下内容不起作用,但为了清楚起见,我正在将列表中的列表读入main.py ,如下所示:
self.values = config['INPUT']['values']
self
is there because I am using a class. self
在那里,因为我使用的是 class。 These are my declarations in the beginning of main.py :这些是我在main.py开头的声明:
import configparser
config = configparser.ConfigParser()
config.sections()
config.read('config.ini')
You can store a list (or list of lists or dict or whatever) as a string, and use ast
to recover it.您可以将列表(或列表或字典或其他列表)存储为字符串,并使用
ast
来恢复它。
Config:配置:
[INPUT]
values = [[40000, 60000], [70000, 80000]]
And script (simplified as reading string variable from config is not a problem):和脚本(简化为从配置中读取字符串变量不是问题):
import ast
list_in_list = ast.literal_eval(string_var_read_from_config)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.