2

i am trying to read some header values from config file in python while creating CSV.

Working Python file:

headers = ['Column1','Column2','Column3']
...
writer.writerow(header)
...

Using Config: text.conf

[CSV]
headers = 'Column1','Column2','Column3'

Python file

config = configparser.ConfigParser()
config.read(text.conf)
header = config['CSV'].get('headers')

But my csv file looks something like this,

',C,o,l,u,m,n,1,',",",',C,o,l,u,m,n,2,',",",',C,o,l,u,m,n,3,'

Expected:

Column1,Column2,Column3
Satscreate
  • 495
  • 12
  • 38
  • 2
    The value of `header` is `"'Column1','Column2','Column3'"`, you need to process that further for the output you expect. – jonrsharpe Oct 15 '20 at 11:25
  • 1
    From the docs: "Config parsers provide option value getters that perform type conversion. By default ``getint``(), ``getfloat``(), and ``getboolean``() are implemented." If you want to support a `getlistofstrings`, you must define it. – MisterMiyagi Oct 15 '20 at 11:31

1 Answers1

2

You are getting a string object and not a list. You can either process the string to a list

Ex:

config = configparser.ConfigParser()
config.read(text.conf)
header = [i.strip("'") for i in config['CSV'].get('headers').split(",")]

Or add [] --> headers = ['Column1','Column2','Column3'] to the config file and use the ast module to convert it to a list

Ex:

headers = ['Column1','Column2','Column3']
print(ast.literal_eval(config['CSV']['headers']))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Thanks a lot folks. i did this, header = config['CSV'].get('headers').split(",") and config file has headers = Column1,Column2,Column3 – Satscreate Oct 15 '20 at 11:42