ConfigParser with Unicode items ConfigParser with Unicode items python python

ConfigParser with Unicode items


The ConfigParser.readfp() method can take a file object, have you tried opening the file object with the correct encoding using the codecs module before sending it to ConfigParser like below:

cfg.readfp(codecs.open("myconfig", "r", "utf8"))

For Python 3.2 or above, readfp() is deprecated. Use read_file() instead.


In python 3.2 encoding parameter was introduced to read(), so it can now be used as:

cfg.read("myconfig", encoding='utf-8')


Try to overwrite the write function in RawConfigParser() like this:

class ConfigWithCoder(RawConfigParser):def write(self, fp):    """Write an .ini-format representation of the configuration state."""    if self._defaults:        fp.write("[%s]\n" % "DEFAULT")        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):                if type(value) == unicode:                    value = ''.join(value).encode('utf-8')                else:                    value = str(value)                value = value.replace('\n', '\n\t')                key = " = ".join((key, value))            fp.write("%s\n" % (key))        fp.write("\n")