Python ConfigParser module rename a section

2020-02-16 01:51发布

问题:

How can you rename a section in a ConfigParser object?

回答1:

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


回答2:

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)