注:作者编程小白,高手勿喷,如有疏漏,还请指正!
因业余爱好需要,发现现有的 ConfigParser 模块在写入数据时会删除注释,不利于配置文件对于用户而言的可读性,网上找了一圈,看得云里雾里,所以尝试自己在不通过修改源文件(也没这能力)的情况下,来临时解决一下问题。
例,原 test.ini 文件内容如下
[sect1]
# cmt 1.1
opt1 = 1
# cmt 1.2
opt2 = 2
# cmt 1.3
opt3 = 0
[sect2]
# cmt 2.1
opt1 = 3
# cmt 2.2
opt2 = 4
直接使用 ConfigParser 更改 opt3 的值为 33,python 代码如下
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read("test.ini", encoding = "utf-8")
cfg.set("sect1", "opt3", "33")
with open("test.ini", "w+") as f:
cfg.write(f)
f.close()
运行结果如下,可以看到原有的 comment 都丢失了,
[sect1]
opt1 = 1
opt2 = 2
opt3 = 33
[sect2]
opt1 = 3
opt2 = 4
临时的解决方案如下,但很显然存在诸多问题,目前只能覆盖修改存在 section / option 对应 value 的场景,待后续深入研究再想办法解决(貌似理论上无解啊,新增/删除怎么搞?)