views:

34

answers:

1

Is there an easy way to rename a section in a config file using ConfigParser in python? I'd prefer not to have to delete the section and recreate it, but that is my only answer right now.

A: 

No. The builtin ConfigParser stores sections as _sections, which is a dict. Since this is python you could access that variable to do an easy copy. (config._sections[new_name] = config._sections[old_name]; config._sections.pop(old_name)

But ConfigParser may change at some later date and this would break your implementation.

Therefore I don't recommend doing that, alternatively you could subclass ConfigParser and implement a delete_section or change the way options are stored.

iondiode
Thanks. I implemented deleting the sections that I wanted to rename and then recreating them. Now my issue is they get totally out of order. How does the parser add new sections? Is it to the beginning of the file or the end?
Falmarri
since the base type is dict for the _sections variable you cannot get a guaranteed order for items within a section. You would need to override alot of the ConfigParser class. Some alternatives are discussed herehttp://wiki.python.org/moin/ConfigParserShootout
iondiode