Python - 如何使用 python configParser 从配置文件 (INI) 中读取列表值
Python - How to read list values from config file (INI) using python configParser
我试图在创建 CSV 时从 python 中的配置文件中读取一些 header 值。
工作 Python 文件:
headers = ['Column1','Column2','Column3']
...
writer.writerow(header)
...
使用配置:
text.conf
[CSV]
headers = 'Column1','Column2','Column3'
Python 文件
config = configparser.ConfigParser()
config.read(text.conf)
header = config['CSV'].get('headers')
但是我的 csv 文件看起来像这样,
',C,o,l,u,m,n,1,',",",',C,o,l,u,m,n,2,',",",',C,o,l,u,m,n,3,'
预期:
Column1,Column2,Column3
您得到的是一个字符串对象,而不是一个列表。您可以将字符串处理为列表
例如:
config = configparser.ConfigParser()
config.read(text.conf)
header = [i.strip("'") for i in config['CSV'].get('headers').split(",")]
或者将[]
--> headers = ['Column1','Column2','Column3']
添加到配置文件中,使用ast
模块将其转换为列表
例如:
headers = ['Column1','Column2','Column3']
print(ast.literal_eval(config['CSV']['headers']))
我试图在创建 CSV 时从 python 中的配置文件中读取一些 header 值。
工作 Python 文件:
headers = ['Column1','Column2','Column3']
...
writer.writerow(header)
...
使用配置: text.conf
[CSV]
headers = 'Column1','Column2','Column3'
Python 文件
config = configparser.ConfigParser()
config.read(text.conf)
header = config['CSV'].get('headers')
但是我的 csv 文件看起来像这样,
',C,o,l,u,m,n,1,',",",',C,o,l,u,m,n,2,',",",',C,o,l,u,m,n,3,'
预期:
Column1,Column2,Column3
您得到的是一个字符串对象,而不是一个列表。您可以将字符串处理为列表
例如:
config = configparser.ConfigParser()
config.read(text.conf)
header = [i.strip("'") for i in config['CSV'].get('headers').split(",")]
或者将[]
--> headers = ['Column1','Column2','Column3']
添加到配置文件中,使用ast
模块将其转换为列表
例如:
headers = ['Column1','Column2','Column3']
print(ast.literal_eval(config['CSV']['headers']))