Keep ConfigParser output files sorted

前端 未结 4 852
旧巷少年郎
旧巷少年郎 2021-01-05 10:15

I\'ve noticed with my source control that the content of the output files generated with ConfigParser is never in the same order. Sometimes sections will change place or opt

4条回答
  •  遥遥无期
    2021-01-05 10:54

    If you want to take it a step further than Alexander Ljungberg's answer and also sort the sections and the contents of the sections you can use the following:

    config = ConfigParser.ConfigParser({}, collections.OrderedDict)
    config.read('testfile.ini')
    # Order the content of each section alphabetically
    for section in config._sections:
        config._sections[section] = collections.OrderedDict(sorted(config._sections[section].items(), key=lambda t: t[0]))
    
    # Order all sections alphabetically
    config._sections = collections.OrderedDict(sorted(config._sections.items(), key=lambda t: t[0] ))
    
    # Write ini file to standard output
    config.write(sys.stdout)
    

    This uses OrderdDict dictionaries (to keep ordering) and sorts the read ini file from outside ConfigParser by overwriting the internal _sections dictionary.

提交回复
热议问题