我认为 ConfigParser 模块的 set 方法会更新给定的字段,但是,似乎更改仍然只在内存中,并且不会进入配置文件。这是正常行为吗?
我也尝试了写方法,但我得到的是另一个复制的部分,到目前为止并不是我想要的。
这是一个代表我正在做的事情的样本:
import sys
import ConfigParser
if __name__=='__main__':
cfg=ConfigParser.ConfigParser()
path='./../whatever.cfg/..'
c=cfg.read(path)
print cfg.get('fan','enabled')
cfg.set('fan','enabled','False')
c=cfg.read(path)
print cfg.get('fan','enabled')
答案 0 :(得分:9)
答案 1 :(得分:3)
是的,set
操作内存中的信息而不是最初读取信息的文件是正常的。
write
应该是你想要的。你究竟是如何使用它的,它到底做了什么,以及它与你想要的有什么不同?
顺便说一下,除非有特殊原因,否则您通常应使用ConfigParser.SafeConfigParser
而不是ConfigParser.ConfigParser
。
继续使用Python 3.x SafeConfigParser
将合并/重命名为ConfigParser
,因此SafeConfigParser
最终将被弃用并逐步淘汰。
答案 2 :(得分:1)
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('properties.ini')
dhana = {'key': 'valu11'}
parser.set('CAMPAIGNS', 'zoho_next_campaign_map', str(dhana))
with open("properties.ini", "w+") as configfile:
parser.write(configfile)
答案 3 :(得分:0)
我遇到了同样的问题,并发现这对我有用:
def update_system_status_values(file, section, system, value):
config.read(file)
cfgfile = open(file, 'w')
config.set(section, system, value)
config.write(cfgfile)
cfgfile.close()
1)阅读
2)打开它
3)更新它
4)写下来
5)关闭它