7

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.

2 Answers 2

8

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())
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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.
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.