python - 配置解析器 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()
提前致谢
解决方案
尝试对 进行子类化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")
...
除此之外,您的代码中还有两个错误:
您没有打开文件进行写入。
你有不平衡的括号。
两者都应该阻止代码运行。
推荐阅读
- python - 在点周围创建网格的 numpy 有效方法
- typescript - Typescript 未知类型不能与 ? 一起使用。操作员
- javascript - 以不可变的方式更新其值是对象数组的对象
- java - java中由ExceptionInitializerError引起的InvocationTargetException是什么意思?
- string - 无法将浮点数连接到字符串
- sparql - 优化 SPARQL 查询性能问题
- javascript - 为什么删除类不起作用?
- typescript - undefined 和 void 有什么区别?
- mysql - 当相同的条件在 IF 语句中起作用时,为什么使用 HAVING 会消除输出?
- python-2.7 - 尝试在 Mac 上更新 Ansible