I don't care if it's JSON
, pickle
, YAML
, or whatever.
All other implementations I have seen are not forwards compatible, so if I have a config file, add a new key in the code, then load that config file, it'll just crash.
Are there any simple way to do this?
ConfigParser Basic example
The file can be loaded and used like this:
which outputs
As you can see, you can use a standard data format that is easy to read and write. Methods like getboolean and getint allow you to get the datatype instead of a simple string.
Writing configuration
results in
XML Basic example
Seems not to be used at all for configuration files by the Python community. However, parsing / writing XML is easy and there are plenty of possibilities to do so with Python. One is BeautifulSoup:
where the config.xml might look like this
If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.
INI file has the format:
Save and load a dictionary. You will have arbitrary keys, values and arbitrary number of key, values pairs.
Configuration files in python
There are several ways to do this depending on the file format required.
ConfigParser [.ini format]
I would use the standard configparser approach unless there were compelling reasons to use a different format.
Write a file like so:
The file format is very simple with sections marked out in square brackets:
Values can be extracted from the file like so:
JSON [.json format]
JSON data can be very complex and has the advantage of being highly portable.
Write data to a file:
Read data from a file:
YAML
A basic YAML example is provided in this answer. More details can be found on the pyYAML website.