How to remove a section from an ini file using Python ConfigParser?

ultimoo picture ultimoo · May 17, 2016 · Viewed 8.1k times · Source

I am attempting to remove a [section] from an ini file using Python's ConfigParser library.

>>> import os
>>> import ConfigParser
>>> os.system("cat a.ini")
[a]
b = c

0

>>> p = ConfigParser.SafeConfigParser()
>>> s = open('a.ini', 'r+')
>>> p.readfp(s)
>>> p.sections()
['a']
>>> p.remove_section('a')
True
>>> p.sections()
[]
>>> p.write(s)
>>> s.close()
>>> os.system("cat a.ini")
[a]
b = c

0
>>>

It appears that the remove_section() happens only in-memory and when asked to write back the results to the ini file, there is nothing to write.

Any ideas on how to remove a section from the ini file and persist it?

Is the mode that I'm using to open the file incorrect? I tried with 'r+' & 'a+' and it didn't work. I cannot truncate the entire file since it may have other sections that shouldn't be deleted.

Answer

BrenBarn picture BrenBarn · May 17, 2016

You need to open the file in write mode eventually. This will truncate it, but that is okay because when you write to it, the ConfigParser object will write all the sections that are still in the object.

What you should do is open the file for reading, read the config, close the file, then open the file again for writing and write it. Like this:

with open("test.ini", "r") as f:
    p.readfp(f)

print(p.sections())
p.remove_section('a')
print(p.sections())

with open("test.ini", "w") as f:
    p.write(f)

# this just verifies that [b] section is still there
with open("test.ini", "r") as f:
    print(f.read())