简体   繁体   中英

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

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.

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.

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

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