在Python ConfigParser中按字母排序导出

7 投票
5 回答
5182 浏览
提问于 2025-04-15 17:30

有没有办法让RawConfigParser.write()这个方法导出的配置文件按照字母顺序排列呢?

即使原来的配置文件是排好序的,这个模块在处理时会把各个部分和选项随意混合在一起,这样手动编辑一个很大的无序配置文件真的很麻烦。

补充说明:我使用的是Python 2.6。

5 个回答

2

这是我写配置文件时按字母顺序排列的解决方案:

class OrderedRawConfigParser( ConfigParser.RawConfigParser ):
"""
Overload standart Class ConfigParser.RawConfigParser
"""
def __init__( self, defaults = None, dict_type = dict ):
    ConfigParser.RawConfigParser.__init__( self, defaults = None, dict_type = dict )

def write(self, fp):
    """Write an .ini-format representation of the configuration state."""
    if self._defaults:
        fp.write("[%s]\n" % DEFAULTSECT)
        for key in sorted( self._defaults ):                
            fp.write( "%s = %s\n" % (key, str( self._defaults[ key ] ).replace('\n', '\n\t')) )                 
        fp.write("\n")
    for section in self._sections:
        fp.write("[%s]\n" % section)
        for key in sorted( self._sections[section] ): 
            if key != "__name__":
                fp.write("%s = %s\n" %
                         (key, str( self._sections[section][ key ] ).replace('\n', '\n\t')))    
        fp.write("\n")    
4

我通过在外部对ConfigParser中的各个部分进行排序,成功解决了这个问题,代码如下:

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)
3

有三种解决办法:

  1. 传入一个字典类型(作为构造函数的第二个参数),这样可以按照你想要的顺序返回键。
  2. 扩展这个类,并重写 write() 方法(你可以直接复制原来的方法,然后进行修改)。
  3. 复制 ConfigParser.py 文件,并在 write() 方法中添加排序功能。

可以查看 这篇文章了解有序字典,或者使用 这个实现,它可以保持原来的添加顺序。

撰写回答