editing conf file

Tim Chase python.list at tim.thechases.com
Fri Nov 16 14:43:11 CET 2012

On 11/16/12 07:04, Thomas Bach wrote:
> On Fri, Nov 16, 2012 at 01:48:49PM +0100, chip9munk wrote:
>> configparser has four functions: get, getboolean, getfloat and getint.
>> how do I get list from cfg file?!
> AFAIK you have to parse the list yourself. Something like
> my_list = [ s.strip() for s in cp.get('section', 'option').split(',') ]
> if you use a comma as a separator.

For slightly more complex option text, you can use the CSV module to
do the heavy lifting, so if you have something like

  option="one, one, one",two,3

then you can have Python give you

  my_list = next(csv.reader([cp.get("section", "option")]))

or alternatively use the shlex module and separate them like shell

  option="one, one, one" two 3

then do

  my_list = list(shlex.shlex(cp.get("section", "option")))

Or yet one more way using Python list syntax for literals:

  option=["one, one, one", "two", 3]

and get them with

  my_list = ast.literal_eval(cp.get("section", "option))

Lots of fun (and batteries-included) ways depending on how you want
to represent the list in the config file and what sorts of data it
can contain.


More information about the Python-list mailing list