The*_*Guy 6 python configuration-files
我有点卡住了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:
Run Code Online (Sandbox Code Playgroud)
然后它显示:
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
>>>
Run Code Online (Sandbox Code Playgroud)
编辑#1
现在我尝试使用iniparse模块.我做了:
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()
Run Code Online (Sandbox Code Playgroud)
不幸的是,它删除了旧内容.我怎么解决这个问题?
编辑#2
看起来它现在有效.
f = open('/etc/yum.repos.d/epel.repo', 'wb')
Run Code Online (Sandbox Code Playgroud)
做了伎俩.
只是,
with open('epel.cfg', 'wb') as configfile:
config.write(configfile)
Run Code Online (Sandbox Code Playgroud)
请参阅此处以获取示例和文档.
您正在寻找的方法是Config.write
.
例如,请参阅文档中的第一个示例
它应该接受一个类似文件的对象来写入配置数据。例如:
with open('new_config.cfg', 'w') as fout:
Config.write(fout)
Run Code Online (Sandbox Code Playgroud)