I'm using the Python module iniparse to save keys to an INI file, but I was wondering if there is a way to delete keys and sections from the INI file using iniparse
. I know it's possible using ConfigParser and that iniparse
is backwards compatible with ConfigParser
, but I can't figure out how to perform the deletions using the same iniparse
object.
from iniparse import INIConfig, RawConfigParser
cfg = INIConfig(open('options.ini'))
print cfg.section.option
cfg.section.option = 'new option'
# Maybe I need to use RawConfigParser somehow?
cfg.remove_option('section','option')
cfg.remove_section('section')
f = open('options.ini', 'w')
print >>f, cfg
f.close()
To remove a section or an option you simply need to delete it. Your revised code would be:
from iniparse import INIConfig
cfg = INIConfig(open('options.ini'))
print cfg.section.option
cfg.section.option = 'new option'
del cfg.section.option
del cfg.section
f = open('options.ini', 'w')
print >>f, cfg
f.close()
Note that if you want to delete a whole section you don't need to delete its options before: just delete the section.
Note also that this way of doing it feels more Pythonic than using remove_option
and remove_section
methods.