Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export with alphabetical sort in Python ConfigParser

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

like image 885
Htechno Avatar asked Dec 31 '09 09:12

Htechno


People also ask

What does Configparser do in Python?

The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have . INI extension.

How do I read a list in Configparser?

Call ConfigParser. read(filename) to read the config data from filename into the ConfigParser object. Call ConfigParser. get(section, option) with option as the JSON-encoded list in section to return the raw string value of the list.

Is Configparser case sensitive?

Note also that keys in sections are case-insensitive and stored in lowercase 1. It is possible to read several configurations into a single ConfigParser , where the most recently added configuration has the highest priority.

Is Configparser built in Python?

configparser comes from Python 3 and as such it works well with Unicode. The library is generally cleaned up in terms of internal data storage and reading/writing files.


1 Answers

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.

like image 82
Aaron Digulla Avatar answered Sep 18 '22 10:09

Aaron Digulla