【问题标题】:Python - How to read list values from config file (INI) using python configParser [duplicate]Python - 如何使用 python configParser 从配置文件(INI)中读取列表值
【发布时间】:2020-10-15 11:22:02
【问题描述】:

我正在尝试在创建 CSV 时从 python 中的配置文件中读取一些标头值。

工作 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

【问题讨论】:

  • header 的值为"'Column1','Column2','Column3'",您需要进一步处理以获得您期望的输出。
  • 来自文档:“配置解析器提供了执行类型转换的选项值获取器。默认情况下实现了 getint()、getfloat() 和 getboolean()。”如果你想支持getlistofstrings,你必须定义它。

标签: python csv configparser


【解决方案1】:

你得到的是一个字符串对象而不是一个列表。您可以将字符串处理为列表

例如:

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

【讨论】:

  • 非常感谢大家。我这样做了, header = config['CSV'].get('headers').split(",") 并且配置文件有 headers = Column1,Column2,Column3
猜你喜欢
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2015-03-13
  • 2013-03-23
  • 2016-09-12
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
相关资源
最近更新 更多