kabik
kabik

Reputation: 55

Python new section in config class

I am trying to write a dynamic config .ini Where I could add new sections with key and values also I could add key less values. I have written a code which create a .ini. But the section is coming as 'default'. Also it is just overwriting the file every time with out adding new section.

I have written a code in python 3 to create a .ini file.

import configparser


"""Generates the configuration file with the config class. 
The file is a .ini file"""


class Config:

    """Class for data in uuids.ini file management"""

    def __init__(self):

        self.config = configparser.ConfigParser()
        self.config_file = "conf.ini"

       # self.config.read(self.config_file)

    def wrt(self, config_name={}):


        condict = {

            "test": "testval",
            'test1': 'testval1',
            'test2': 'testval2'

        }

        for name, val in condict.items():

            self.config.set(config_name, name, val)

        #self.config.read(self.config_file)

        with open(self.config_file, 'w+') as out:
            self.config.write(out)


if __name__ == "__main__":
    Config().wrt()

I should be able to add new sections with key or with out keys. Append keys or value. It should have proper section name.

Upvotes: 0

Views: 540

Answers (1)

Perplexabot
Perplexabot

Reputation: 1989

Some problems with your code:

  • The usage of mutable objects as default parameters can be a little tricky and you may see unexpected behavior.
  • You are using config.set() which is legacy.
  • you are defaulting config_name to a dictionary, why?
  • Too much white space :p
  • You don't need to iterate through the dictionary items to write them using the newer (none legacy) function, as shown below

This should work:

"""Generates the configuration file with the config class.

The file is a .ini file
"""
import configparser
import re


class Config:
    """Class for data in uuids.ini file management."""

    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config_file = "conf.ini"

    # self.config.read(self.config_file)

    def wrt(self, config_name='DEFAULT', condict=None):
        if condict is None:
            self.config.add_section(config_name)
            return

        self.config[config_name] = condict

        with open(self.config_file, 'w') as out:
            self.config.write(out)

        # after writing to file check if keys have no value in the ini file (e.g: key0 = )
        # the last character is '=', let us strip it off to only have the key
        with open(self.config_file) as out:
            ini_data = out.read()

        with open(self.config_file, 'w') as out:
            new_data = re.sub(r'^(.*?)=\s+$', r'\1', ini_data, 0, re.M)
            out.write(new_data)
            out.write('\n')


condict = {"test": "testval", 'test1': 'testval1', 'test2': 'testval2'}

c = Config()

c.wrt('my section', condict)
c.wrt('EMPTY')
c.wrt(condict={'key': 'val'})
c.wrt(config_name='NO_VALUE_SECTION', condict={'key0': '', 'key1': ''})

This outputs:

[DEFAULT]
key = val

[my section]
test = testval
test1 = testval1
test2 = testval2

[EMPTY]

[NO_VALUE_SECTION]
key1 
key0 

Upvotes: 1

Related Questions