There are several solutions to parse configuration files in Python.
These are usually text files contain a list of options with a name and a value, such as "port=8080" or "user: admin". More elaborate configuration files such as "INI files" on Windows contain sections to organize options. A section starts with a name between square brackets, such as "[section1]".
ConfigParser for INI files with sections
See http://docs.python.org/library/configparser.html
This parser is powerful, but it does not support simple configuration files without sections.
SimpleConfigParser for config files without sections
As Fredrik Lundh proposed on the python-dev mailing-list, it is quite simple to extend ConfigParser to support files without sections: http://mail.python.org/pipermail/python-dev/2002-November/029987.html
I have made a module called SimpleConfigParser based on that idea, that you can reuse in your own projects. See attached file below.
Sample usage:
import SimpleConfigParser
filename = 'sample_config_no_section.ini'
cp = SimpleConfigParser.SimpleConfigParser()
cp.read(filename)
print 'getoptionslist():', cp.getoptionslist()
for option in cp.getoptionslist():
print "getoption('%s') = '%s'" % (option, cp.getoption(option))
print "hasoption('wrongname') =", cp.hasoption('wrongname')
|
ConfigObj for more advanced config files
ConfigObj is able to handle INI config files with sections and subsections, among other enhancements.
see http://www.voidspace.org.uk/python/configobj.html
ElementTree for XML config files
see http://www.decalage.info/en/python/etree
Custom config file parser
In fact it is very easy to create your own configuration file parser, thanks to Python string methods such as split() and strip(). For example the following function is able to parse simple configurations files and return a dictionary of parameters:
COMMENT_CHAR = '#' OPTION_CHAR = '=' def parse_config(filename): options = {} f = open(filename) for line in f: # First, remove comments: if COMMENT_CHAR in line: # split on comment char, keep only the part before line, comment = line.split(COMMENT_CHAR, 1) # Second, find lines with an option=value: if OPTION_CHAR in line: # split on option char: option, value = line.split(OPTION_CHAR, 1) # strip spaces: option = option.strip() value = value.strip() # store in dictionary: options[option] = value f.close() return options options = parse_config('config.ini') print options |