在ConfigParser中使用冒号的Python

5 投票
1 回答
3903 浏览
提问于 2025-04-16 06:19

根据文档的说明:

配置文件由多个部分组成,每个部分都有一个以 [section] 开头的标题,后面跟着名称: 值的条目,格式类似于 RFC 822(具体见第3.1.1节,“长标题字段”);同时也可以使用 name=value 的格式。Python 文档

不过,写配置文件时总是使用等号(=)。有没有办法使用冒号(:)呢?

提前谢谢你。

H

1 个回答

7

如果你查看一下在 ConfigParser.py 文件中定义的 RawConfigParser.write 方法的代码,你会发现等号是写死在代码里的。所以,如果你想改变这个行为,你可以创建一个新的类,继承你想使用的 ConfigParser:

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

filename='/tmp/testconfig'    
with open(filename,'w') as f:
    parser=MyConfigParser()
    parser.add_section('test')
    parser.set('test','option','Spam spam spam!')
    parser.set('test','more options',"Really? I can't believe it's not butter!")
    parser.write(f)

这样就能得到:

[test]
more options : Really? I can't believe it's not butter!
option : Spam spam spam!

撰写回答