Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does ConfigParser preserve the order of sections from file?

The order of the sections in my INI file is important.

Apparently, when I use ConfigParser.sections(), the order of sections in the returned list is the same as in the file. But is this guaranteed? I couldn’t find this detail in documentation.

If not, what is the best approach to informing the order of sections?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example:

import configparser

ini_file= """
[Section 1]
option = value

[Section 2]
another = val
"""

config = configparser.ConfigParser()
config.read_string(ini_file)
config.sections()

The return value I get is ['Section 1', 'Section 2']. Is this always the case?

>Solution :

Yes, because the sections are added to an internal dictionary as the file is being read line by line. As of Python version 3.7, dictionaries are ordered, therefore the sections should be in the order you define them in the config file.

Inspecting the source code of configparser, you can see the sections are stored inside self._dict:

Which is a standard Python dict object:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading