Sort ini configuration file in python 3

Home   »   Sort ini configuration file in python 3


import sys
from configparser import ConfigParser


def sort_file(parser, file_name='sorted.ini'):
    sorted_parser = ConfigParser()
    sections = sorted(parser._sections)
    for s in sections:
        sorted_parser.add_section(s)
        items = sorted(parser._sections[s].items())
        for i in items:
            sorted_parser.set(s, i[0], i[1])

    write_sorted_configuration_to_file(file_name, sorted_parser)


def write_sorted_configuration_to_file(file_name, sorted_parser):
    with open(file_name, 'w') as configfile:
        sorted_parser.write(configfile)


def read_file(file_path):
    parser = ConfigParser()
    parser.read(file_path)
    return parser


if __name__ == "__main__":
    ini_file_path = 'default.ini'
    out_file = 'sorted.ini'
    if len(sys.argv[1:]) >= 1:
        ini_file_path = sys.argv[1:][1]
    if len(sys.argv[1:]) >= 2:
        out_file = sys.argv[1:][2]
    parser_config = read_file(ini_file_path)
    sort_file(parser_config, out_file)
    print(f'Wrote sorted file here: {out_file}!')

Leave a Reply

Your email address will not be published. Required fields are marked *