ConfigParser-写入现有节

2024-04-26 21:48:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点拘泥于ConfigParser

我想给现有的部分添加一个特定的设置。

我知道:

import ConfigParser
Config = ConfigParser.ConfigParser()
Config
Config.read("/etc/yum.repos.d/epel.repo")
Config.sections()
Config.set('epel','priority',10)
with open('/etc/yum.repos.d/epel.repo', 'w') as fout:

然后它显示:

...
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block
>>>

编辑1

现在我用InParse模块尝试了一下。我做到了:

from iniparse import INIConfig
cfg = INIConfig(open('/etc/yum.repos.d/epel.repo'))
cfg.epel.priority=10
f = open('/etc/yum.repos.d/epel.repo', 'w')
print >>f, cfg
f.close()

不幸的是,它删除了旧内容。我该怎么解决?

编辑2

看来现在它能用了。

f = open('/etc/yum.repos.d/epel.repo', 'wb')

成功了。


Tags: importconfig编辑readetcrepoopencfg
2条回答

你要找的方法是Config.write

例如,请参见first example in the docs

它应该接受一个类文件的对象来写入配置数据。e、 g.:

with open('new_config.cfg', 'w') as fout:
    Config.write(fout)

很简单

   with open('epel.cfg', 'wb') as configfile:
        config.write(configfile)

有关示例和文档,请参见here

相关问题 更多 >