Python – Export with alphabetical sort in Python ConfigParser

configparserconfiguration-filespython

Is there any solution to force the RawConfigParser.write() method to export the config file with an alphabetical sort?

Even if the original/loaded config file is sorted, the module mixes the section and the options into the sections arbitrarily, and is really annoying to edit manually a huge unsorted config file.

PD: I'm using python 2.6

Best Answer

Three solutions:

  1. Pass in a dict type (second argument to the constructor) which returns the keys in your preferred sort order.
  2. Extend the class and overload write() (just copy this method from the original source and modify it).
  3. Copy the file ConfigParser.py and add the sorting to the method write().

See this article for a ordered dict or maybe use this implementation which preserves the original adding order.