0

Here is my ini file

[456789a]
IP=192.168.1.73
AGENTID=1
NEEDSYNCDEFBAK=-1
GROUP=5
[123456]
IP=192.168.1.73
AGENTID=2
NEEDSYNCDEFBAK=-1
GROUP=2

So..Can I just use configparser to change the name of a section(like..456789a)?

if can't, here is another solution.

  1. read ini file
  2. find "[456789a]"
  3. replace "[4567891]" to "[name]"
  4. use configparser reread this ini file.
0neSe7en
  • 37
  • 1
  • 10

1 Answers1

1

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.

kartikg3
  • 2,590
  • 1
  • 16
  • 23