使用 ConfigParser -Python- 更新字段
我认为 ConfigParser 模块的 set 方法会更新给定的字段,但是,似乎更改仅保留在内存中,不会进入配置文件。这是正常行为吗?
我也尝试过 write 方法,但我得到的是另一个复制的部分,到目前为止这不是我想要的。
这是一个代表我正在做的事情的样本:
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')
I thought that the set method of ConfigParser module updates the field given, but, it seems that the change remains only in memory and doesn't get into the config file. Is it a normal behaviour?
I have also tried the write method, but what I got was another replicated section which by so far is not what I want.
Here is a specimen which represents what I'm doing:
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')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我遇到了同样的问题,并发现这对我有用:
1)阅读它
2)打开它
3)更新它
4)写它
5)关闭它
I ran into the same issue and figure out that this worked for me:
1) Read it
2) Open it
3) Update it
4) Write it
5) Close it
是的,
set
对内存中的信息进行操作,而不是对最初读取信息的文件进行操作,这是正常的。write
应该是你想要的。您到底是如何使用它的,它到底做了什么,以及它与您想要的有何不同?顺便说一句,除非有特殊原因,否则您通常应该使用 ConfigParser.SafeConfigParser 而不是 ConfigParser.ConfigParser 。
随着 Python 3.x 的发展,
SafeConfigParser
将合并/重命名为ConfigParser
,因此SafeConfigParser
最终将被弃用并逐步淘汰。Yes, it is normal that
set
operates on the information in memory rather than on the file from which the information was originally read.write
ought to be what you want. How exactly did you use it, what exactly did it do, and how did that differ from what you wanted?Incidentally, you should generally be using
ConfigParser.SafeConfigParser
rather thanConfigParser.ConfigParser
unless there's a specific reason for doing otherwise.Moving forward with Python 3.x
SafeConfigParser
will be merged/renamed asConfigParser
soSafeConfigParser
will eventually be deprecated and phased out.