从 config.ini 文件中获取列表
Get a list from config.ini file
在我的配置文件中有类似的东西:
[Section_1]
List=Column1,Column2,Column3,Column4
现在,我想在我的主文件中将其作为普通列表处理:
config = configparser.ConfigParser()
config.read("configTab.ini")
for index in range(len(List)):
sql=sql.replace(List[index],"replace("+List[index]+","'hidden'")")
现在当我从配置文件中读取时 "List" 是一个普通的字符串。
最好的方法是什么?
如果我以这种方式在我的主代码中放置一个普通的列表变量:
List=['Column1','Column2','Column3','Column4']
然后它工作正常,但我想从我的配置文件中获取它,
谢谢
使用str.split
:
List = List.split(',')
string = 'a, b, c'
print(string.split(','))
>> ['a', 'b', 'c']
@DeepSpace 的回答并不完全正确。 'b' 和 'c' 周围的前导空格包含在输出中,如果按照写入的方式执行这一行(例如 'b' 实际上是 'b')。
要避免前导和尾随空格,请尝试:
string = 'a, b, c'
print([i.strip() for i in string.split(',')])
>> ['a', 'b', 'c']
在我的配置文件中有类似的东西:
[Section_1]
List=Column1,Column2,Column3,Column4
现在,我想在我的主文件中将其作为普通列表处理:
config = configparser.ConfigParser()
config.read("configTab.ini")
for index in range(len(List)):
sql=sql.replace(List[index],"replace("+List[index]+","'hidden'")")
现在当我从配置文件中读取时 "List" 是一个普通的字符串。 最好的方法是什么?
如果我以这种方式在我的主代码中放置一个普通的列表变量:
List=['Column1','Column2','Column3','Column4']
然后它工作正常,但我想从我的配置文件中获取它,
谢谢
使用str.split
:
List = List.split(',')
string = 'a, b, c'
print(string.split(','))
>> ['a', 'b', 'c']
@DeepSpace 的回答并不完全正确。 'b' 和 'c' 周围的前导空格包含在输出中,如果按照写入的方式执行这一行(例如 'b' 实际上是 'b')。
要避免前导和尾随空格,请尝试:
string = 'a, b, c'
print([i.strip() for i in string.split(',')])
>> ['a', 'b', 'c']