How can you rename a section in a ConfigParser
object?
Asked
Active
Viewed 2,412 times
2
-
1probably duplicate of http://stackoverflow.com/questions/3452788/rename-config-ini-section-using-configparser-in-python – yuwang Feb 25 '13 at 14:25
-
@yuwang When you find a duplicate, please flag the question instead of posting a comment (flag link under the question). If you flag, a comment will be generated automatically and the question will enter a review queue accessible to all users that have the ability to vote to close. – yannis Feb 25 '13 at 15:15
-
possibly avoid closing as this answer contains actual code to solve the issue - not the case for the linked question – bph Mar 05 '13 at 12:21
-
I found the answer here: http://docs.python.org/3/library/argparse.html#sub-commands. Using sub-commands resolves the issue – Hendré Nov 13 '13 at 16:32
3 Answers
9
example helper function - silly really but it might save someone a few minutes work...
def rename_section(cp, section_from, section_to):
items = cp.items(section_from)
cp.add_section(section_to)
for item in items:
cp.set(section_to, item[0], item[1])
cp.remove_section(section_from)
2
As far as I can tell, you need to
- get the sections items via ConfigParser.items
- remove the section via ConfigParser.remove_section
- create a new section via ConfigParser.add_section
- Put the items back into the new section via ConfigParser.set

mgilson
- 300,191
- 65
- 633
- 696
-
i thought as much - where is cp.set_section("old_name", "new_name") when you need it? – bph Feb 25 '13 at 14:31
-
@Heitt -- Yeah. I've not spent a lot of time reading the configparser source, but it seems like that wouldn't be terribly hard to accomplish. I honestly have always felt like there is a bunch of functionality to configparser which seems like it could be added without much trouble. – mgilson Feb 25 '13 at 14:33
1
You can use the private method _sections
to rename it in a single line.
def rename_config_section(config, old_section, new_section):
"""Rename a section in a configparser object."""
config._sections[new_section] = config._sections.pop(old_section)

Kai Lukowiak
- 63
- 1
- 6