'Iterate over subsections in a config file - Python Configparser

Please advice how do we loop through subsection in Python - configparser.

[KUBENAMESPACE1]
  [MONITOR_CONFIG1]
  DEPLOYMENT_NAME = XXX
  MIN_REPLICAS = 1
  MAX_REPLICAS = 10
  [MONITOR_CONFIG2]
  DEPLOYMENT_NAME = XXX
  MIN_REPLICAS = 1
  MAX_REPLICAS = 10

[KUBENAMESPACE2]


Solution 1:[1]

From the documentation of configparser, it only supports one section level.

It would be much easier and cleaner to maintain this in a JSON file.

{
    "KUBENAMESPACE1": {
        "MONITOR_CONFIG1": {
            "DEPLOYMENT_NAME": "XXX",
            "MIN_REPLICAS": "1",
            "MAX_REPLICAS": "10"
        },
        "MONITOR_CONFIG2": {
            "DEPLOYMENT_NAME": "XXX",
            "MIN_REPLICAS": "1",
            "MAX_REPLICAS": "10"
        }
    },
    "KUBENAMESPACE2": {}
}

Solution 2:[2]

From my working application:

import configparser

config = configparser.ConfigParser()
config.read("settings.ini")

for section in config.sections():
    print(f"[{section}]")
    for key, value in config.items(section):
        print(f"\tfor key {key} -> {value} (value)")

Links:

https://en.wikipedia.org/wiki/INI_file#Format

https://linuxhint.com/python-configparser-example/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vishnudev
Solution 2