I am using ConfigParser to read the runtime configuration of a script.
I would like to have the flexibility of not providing a section name (there are scripts which are simple enough; they don't need a 'section'). ConfigParser will throw the NoSectionError
exception, and will not accept the file.
How can I make ConfigParser simply retrieve the (key, value)
tuples of a config file without section names? For instance:
key1=val1
key2:val2
I would rather not write to the config file.
Having ran into this problem myself, I wrote a complete wrapper to ConfigParser (the version in Python 2) that can read and write files without sections transparently, based on Alex Martelli's approach linked on the accepted answer. It should be a drop-in replacement to any usage of ConfigParser. Posting it in case anyone in need of that finds this page.
The easiest way to do this is to use python's CSV parser, in my opinion. Here's a read/write function demonstrating this approach as well as a test driver. This should work provided the values are not allowed to be multi-line. :)
You can use the ConfigObj library to do that simply : http://www.voidspace.org.uk/python/configobj.html
Updated: Find latest code here.
If you are under Debian/Ubuntu, you can install this module using your package manager :
An example of use:
Enlightened by this answer by jterrace, I come up with this solution:
EDIT for future googlers: As of Python 3.4+
readfp
is deprecated, andStringIO
is not needed anymore. Instead we can useread_string
directly:Alex Martelli provided a solution for using
ConfigParser
to parse.properties
files (which are apparently section-less config files).His solution is a file-like wrapper that will automagically insert a dummy section heading to satisfy
ConfigParser
's requirements.Blueicefield's answer mentioned configobj, but the original lib only supports Python 2. It now has a Python 3+ compatible port:
https://github.com/DiffSK/configobj
APIs haven't changed, see it's doc.