【发布时间】:2011-10-01 00:40:57
【问题描述】:
如何将 cmets 写入节内的给定文件?
如果我有:
import ConfigParser
with open('./config.ini', 'w') as f:
conf = ConfigParser.ConfigParser()
conf.set('DEFAULT', 'test', 1)
conf.write(f)
我会得到文件:
[DEFAULT]
test = 1
但是我怎样才能在[DEFAULT] 部分中获取带有 cmets 的文件,例如:
[DEFAULT]
; test comment
test = 1
我知道我可以通过以下方式将代码写入文件:
import ConfigParser
with open('./config.ini', 'w') as f:
conf = ConfigParser.ConfigParser()
conf.set('DEFAULT', 'test', 1)
conf.write(f)
f.write('; test comment') # but this gets printed after the section key-value pairs
ConfigParser 有可能吗?而且我不想尝试其他模块,因为我需要让我的程序尽可能地保持“库存”。
【问题讨论】:
-
在考虑使用 ConfigParser 编写配置文件后,我决定使用旧的标准文件接口
f = open('test.ini', 'w'); f.write('blabla')编写我的文件,因为 ConfigParser 模块甚至没有按预定义的顺序写入(因为它使用字典,甚至虽然其中一个例子表明写作是按某种顺序进行的:python docs) -
如果你还在,我建议你写一个简短的答案,并将其标记为已接受。即使在此评论之后,我也阅读了建议的答案并得出了相同的结论......但花了我一段时间,我什至投票赞成你选择的解决方案......
标签: python configparser