Is there a way for configparser in python to set a value without having sections in the config file?
If not please tell me of any alternatives.
Thank you.
more info:
So basically I have a config file with format:
Name: value
It's a system file that I want to change the value for a given name. I was wondering if this can be done easily with a module instead of manually writing a parser.
Personally I like to do my config files as XML. An example (taken from the ConfigObj article for comparison purposes) you could create a file called config.xml with the following contents:
In Python, you could then get the values doing something like this:
Now if we look at config.xml we see:
The benefits are the same as that of general XML - it's human readable, there are a number of decent parsers that already exist in pretty much every programming language you can imagine, and it supports grouping and attributes. As an added bonus when your config files get larger you can also incorporate XML validation (using schemas) to find mistakes before runtime.
I know of no way to do that with configparser, which is very section-oriented.
An alternative would be to use the Voidspace Python module named ConfigObj by Michael Foord. In the The Advantages of ConfigObj section of an article he wrote titled An Introduction to ConfigObj, it says:
Emphasis mine.
You could use the
csv
module to do most of work of parsing the file and writing it back out after you made changes -- so it should be relatively easy to use. I got the idea from one of the answers to a similar question titled Using ConfigParser to read a file without section name.However I've made a number of changes to it, including coding it to work in both Python 2 & 3, unhardcoding the key/value delimiter it uses so it could be almost anything (but be a colon by default), along with several optimizations.