Doing a simple search and replace, like in the alternative you have provided, might be risky. It might change some occurrence of that string that you might not want changed.
To guarantee a safe replace, it is better to use the power of ConfigParser
itself. We will use ConfigParser
to implement something similar to your alternative. Here is a pseudo-code/algorithm with some methods you can use to achieve this (customized to your question):
1) Read the ini file using something like:
_config = ConfigParser.ConfigParser()
with open(your_config_file) as config_file:
_config.readfp(config_file)
2) Get all the options as (name, value) pairs for the section you want to rename:
my_section_to_rename = "456789a"
my_section_items = _config.items(section_to_rename)
3) Add a section with the new name you want to give, as a new section:
my_section_new_name = "newSectionName"
_config.add_section(my_section_new_name)
4) Add all the options from the previous section items to this new one:
for option,value in my_section_items:
_config.set(my_section_new_name, option, value)
5) Remove the old section from the ConfigParser
object:
_config.remove_section(my_section_to_rename)
6) Now write this to the ini file to finish up the process.
with open(your_config_file) as config_file:
_config.write(your_config_file)
Check out the docs on all these methods and classes regarding ConfigParser
.
Hope that was useful.