首页 > 解决方案 > 配置解析器 python 2.7。配置写入后分隔符更改为“=”

问题描述

我有一个文件如下所示

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

在我读取并修改一个字段后,分隔符将更改为“=”而不是“:”,如下所示

[SectionOne]
Status = Married
Name = Derek
Value = Yes
Age = 30
Single = True

我正在使用 python 2.7,我现在无法迁移到新版本的 python。

代码如下

Config = ConfigParser.ConfigParser()
Config.read("Bacpypes.ini")
cfgfile = open("Bacpypes.ini")
Config.set('SectionOne', 'Status', 'Married')
Config.write(cfgfile
cfgfile.close()

提前致谢

标签: pythonpython-2.7configparser

解决方案


尝试对 进行子类化ConfigParser以修改其行为,以便编写 a:而不是=

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__":
                    continue
                if (value is not None) or (self._optcre == self.OPTCRE):
                    key = ": ".join((key, str(value).replace('\n', '\n\t')))
                fp.write("%s\n" % (key))
            fp.write("\n")

然后使用MyConfigParser

config = MyConfigParser()
config.read("Bacpypes.ini")
...

除此之外,您的代码中还有两个错误:

  • 您没有打开文件进行写入。

  • 你有不平衡的括号。

两者都应该阻止代码运行。


推荐阅读