Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigParser - Write to existing section

I am a bit stuck at the ConfigParser.

I want to add a specific setting to a existing section.

I do:

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:

Then it shows:

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

    ^
IndentationError: expected an indented block
>>>

Edit #1

Now i tried it with the iniparse module. I did:

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()

Unfortunately it deletes the old content. How can i solve this?

Edit #2

It looks like that it works now.

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

did the trick.

like image 911
TheNiceGuy Avatar asked Dec 03 '13 20:12

TheNiceGuy


2 Answers

Simply,

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

See here for examples and documentation.

like image 98
sPaz Avatar answered Oct 16 '22 15:10

sPaz


The method you're looking for is Config.write.

See, for example, the first example in the docs

It should accept a file-like object to write the config data to. e.g.:

with open('new_config.cfg', 'w') as fout:
    Config.write(fout)
like image 38
mgilson Avatar answered Oct 16 '22 15:10

mgilson