Python – ConfigParser – Write to .ini files

ConfigParser – Write to .ini files… here is a solution to the problem.

ConfigParser – Write to .ini files

I have a config.ini file that contains some of the default configuration for the web application (using Flask for VS 2017).

I also want to write some config myself

I’m trying to write in the [keys] section using the code below, the variable is gkey:

def writeKey(key):
    Config = configparser. ConfigParser()    
    configFile = Path("config.ini")
    if configFile.is_file() == False:
        cfgfile = open("config.ini",'w')
    else:
        cfgfile = open("config.ini")

# add the settings to the structure of the file, and lets write it out...
    Config.add_section('keys')
    Config.set('gkey','key',True)
    Config.write(cfgfile)
    cfgfile.close()

gkey = encrypt(key)
writeKey(gkey)

I get the following error:

Traceback (most recent call last):
  File "C:\Users\blivo\documents\visual studio 2017\Projects\blivori2\blivori2\blivori2\functions\common.py", line 59, in <module>
    writeKey(gkey)
  File "C:\Users\blivo\documents\visual studio 2017\Projects\blivori2\blivori2\blivori2\functions\common.py", line 30, in writeKey
    Config.set('gkey','key',True)
  File "C:\Program Files\Python36\lib\configparser.py", line 1189, in set
    self._validate_value_types(option=option, value=value)
  File "C:\Program Files\Python36\lib\configparser.py", line 1174, in _validate_value_types
    raise TypeError("option values must be strings")
TypeError: option values must be strings

I would like to ask you a question:

  • Is it appropriate to store the configuration in a .ini file? If so, how best to protect it from being read/disclosed by the public.

Solution

Yes, storing the configuration in a .ini file is common practice among many other possible solutions. As for security, I highly recommend storing it in a non-public folder, somewhere outside of your network’s root tree. This allows your Python application to read it, but no network user can download it.

About your error: .ini Option values (and option names) must be strings, so change your line:

Config.set('gkey','key',True)

to

Config.set('gkey','key','True')  # or '1'

The value is then read using Configparser's .getboolean() instead of .get().


In addition, I strongly recommend not to do without with.... Use open() in the case of block. And there doesn’t seem to be a good reason for the if test, which is considered anti-pattern and bad programming practice in Python. Using standard mode can make your code simpler and more robust:

def writeKey(key):
    with open("config.ini", 'w') as cfgfile:
        Config = configparser. ConfigParser()    
        # add the settings to the structure of the file, and lets write it out...
        Config['keys']['gkey'] = key
        Config.write(cfgfile)

Related Problems and Solutions