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

10,414

Solution 1

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

Solution 2

You need to change file position using file.seek. Otherwise, p.write(s) writes the empty string (because the config is empty now after remove_section) at the end of the file.

And you need to call file.truncate so that content after current file position cleared.

p = ConfigParser.SafeConfigParser()
with open('a.ini', 'r+') as s:
    p.readfp(s)  # File position changed (it's at the end of the file)
    p.remove_section('a')
    s.seek(0)  # <-- Change the file position to the beginning of the file
    p.write(s)
    s.truncate()  # <-- Truncate remaining content after the written position.
Share:
10,414
ultimoo
Author by

ultimoo

Updated on June 04, 2022

Comments

  • ultimoo
    ultimoo almost 2 years

    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.

  • ultimoo
    ultimoo about 8 years
    Thanks, this worked. It does rid the file of comments and such, since ConfigParser doesn't parse those. Is there a more featureful Python library recommended for ini parsing?
  • BrenBarn
    BrenBarn about 8 years
    @ultimoo: A quick google suggests ConfigObj. I haven't used it myself. You'd have to check it out to see if it meets your needs.