简体   繁体   中英

ConfigParser python 2.7. Delimiter is getting changed to '=' after config write

I have a file looks like below

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

After i read and modify a field, the delimiter is getting changed to '=' instead of ':' as below

[SectionOne]
Status = Married
Name = Derek
Value = Yes
Age = 30
Single = True

I am using python 2.7 and i cannot migrate to a new version of python now.

the code is below

Config = ConfigParser.ConfigParser()
Config.read("Bacpypes.ini")
cfgfile = open("Bacpypes.ini")
Config.set('SectionOne', 'Status', 'Married')
Config.write(cfgfile
cfgfile.close()

Thanks in advance

Try to subclass the ConfigParser to modify its behaviour so it writes a : instead of = :

class MyConfigParser(ConfigParser.ConfigParser):

    def write(self, fp):
        """Write an .ini-format representation of the configuration state."""
        if self._defaults:
            fp.write("[%s]\n" % DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")
        for section in self._sections:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                if key == "__name__":
                    continue
                if (value is not None) or (self._optcre == self.OPTCRE):
                    key = ": ".join((key, str(value).replace('\n', '\n\t')))
                fp.write("%s\n" % (key))
            fp.write("\n")

Then use MyConfigParser :

config = MyConfigParser()
config.read("Bacpypes.ini")
...

In addition to that there are two errors in your code:

  • You did not open the file for writing.

  • You have unbalanced parentheses.

Both should prevent the code from running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM