Reading array from config file in python

if you can change config format like this:

folder = /home/scorpil
         /media/sda5/
         /media/sdb5/

then in python:

config.get("common", "folder").split("\n")

Your config could be:

[common]
logfile=log.txt
db_host=localhost
db_user=root
db_pass=password
folder = ("/home/scorpil", "/media/sda5/", "/media/sdb5/")

Assuming that you have config in a file named foo.cfg, you can do the following:

import ConfigParser
cp = ConfigParser.ConfigParser()
cp.read("foo.cfg")
folder = eval(cp.get("common", "folder"), {}, {})

print folder
print type(folder)

which should produce:

('/home/scorpil', '/media/sda5/', '/media/sdb5/')
<type 'tuple'>

-- EDIT -- I've since changed my mind about this, and would take the position today that using eval in this context is a bad idea. Even with a restricted environment, if the configuration file is under user control it may be a very bad idea. Today I'd probably recommend doing something interesting with split to avoid malicious code execution.


You can get the items list and use a list comprehension to create a list of all the items which name starts with a defined prefix, in your case folder

folders = tuple([ item[1] for item in configparser.items() if item[0].startswith("folder")])