I know that SafeConfigParser in Python 2.7 doesn't support umlauts. But, whats the pythonic and best why to fix it myself? Below you can see my executable program. It works perfectly without umlauts. However, when I work with umlauts, I get the following error message: config_parser.readfp(StringIO(unicode(default_ini_file))) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 27: ordinal not in range(128)
Well, in the read_in_configuration()-Function you see the comment, why I have to read it with unicode().
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from configparser import SafeConfigParser
except ImportError:
from ConfigParser import SafeConfigParser # ver. < 3.0
from io import StringIO
class DefaultINIFile(object):
def __init__(self):
self.DEFAULT_INI = """[section_a]
umlaut_value = äüö
ascii_value = abcdef
[section_b]
int_value = 10
[section_c]
false_value = False
true_value = True
"""
def read_in_configuration(config_parser, filename, default_ini_file):
# I have to open it with unicode, because I get
# the error: TypeError: initial_value must be unicode or None, not str
config_parser.readfp(StringIO(unicode(default_ini_file)))
config_parser.read(filename)
return config_parser
def update_value(config_parser):
config_parser.set('section_a', 'ascii_value', 'hello world')
def write_ini_file(file_name, config_parser):
with open(file_name, 'w') as config_file:
config_parser.write(config_file)
def add_new_section_value(config_parser):
config_parser.add_section('section_d')
config_parser.set('section_d', 'test_value', 'test')
config_parser.set('section_d', 'unicode_string', 'umlautäöü')
def main():
default_ini_file = DefaultINIFile()
config_parser = SafeConfigParser()
file_path = raw_input("Enter path to file: ")
print "Reading from ini file"
configuration = read_in_configuration(config_parser = config_parser,
filename = file_path,
default_ini_file = default_ini_file.DEFAULT_INI)
print "Updating the config"
update_value(config_parser = configuration)
print "Adding nuew stuff"
add_new_section_value(config_parser = configuration)
print "Getting values"
print(configuration.get('section_a', 'umlaut_value'))
print(configuration.get('section_d', 'unicode_string'))
print "Writing in ini file"
write_ini_file(file_name = file_path,
config_parser = config_parser)
if __name__ == "__main__":
main()