简体   繁体   中英

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.

Simply,

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

See here for examples and documentation.

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. eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM