ConfigObj/ConfigParser vs. using YAML for Python settings file

It depends on what you want to store in your config files and how you use them If you do round tripping (yaml→code→yaml) and want comments preserved you cannot use PyYAML or ConfigParser. If you want to preserve the order of your keys (e.g. when you check in your config files), PyYAML doesn’t do that … Read more

Booleans in ConfigParser always return True

Use getboolean(): print config.getboolean(‘main’, ‘some_boolean’) print config.getboolean(‘main’, ‘some_other_boolean’) From the Python manual: RawConfigParser.getboolean(section, option) A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are “1”, “yes”, “true”, and “on”, which cause this method to return True, and “0”, “no”, “false”, and … Read more

Writing comments to files with ConfigParser

You can use the allow_no_value option if you have Version >= 2.7 This snippet: import ConfigParser config = ConfigParser.ConfigParser(allow_no_value=True) config.add_section(‘default_settings’) config.set(‘default_settings’, ‘; comment here’) config.set(‘default_settings’, ‘test’, 1) with open(‘config.ini’, ‘w’) as fp: config.write(fp) config = ConfigParser.ConfigParser(allow_no_value=True) config.read(‘config.ini’) print config.items(‘default_settings’) will create an ini file like this: [default_settings] ; comment here test = 1

Where to put a configuration file in Python?

Have you seen how configuration files work? Read up on “rc” files, as they’re sometimes called. “bashrc”, “vimrc”, etc. There’s usually a multi-step search for the configuration file. Local directory. ./myproject.conf. User’s home directory (~user/myproject.conf) A standard system-wide directory (/etc/myproject/myproject.conf) A place named by an environment variable (MYPROJECT_CONF) The Python installation would be the last … Read more