import os from configparser import ConfigParser, NoOptionError, NoSectionError, DuplicateSectionError class Config: parser: ConfigParser def __init__(self, filename: str = "config.ini"): """ Config parser reading config.ini Attributes: self.parser: ConfigParser holding list of sections and options self.__filename: Path and name to the config file """ self.parser = ConfigParser() home_path = os.environ["HOME"] full_path = os.path.join(home_path, ".config", "brovski-adress-etiketten" ) if not os.path.exists(full_path): os.makedirs(full_path) self.config_file = os.path.join(full_path, filename) self._load() def _save(self): with open(self.config_file, 'w') as outfile: self.parser.write(outfile) def _load(self): self.parser.read(self.config_file) def add_section(self, section): self._load() try: self.parser.add_section(section) except DuplicateSectionError: return self._save() def set(self, section: str, option: str, value: str): self._load() self.add_section(section) self.parser.set(section, option, value) self._save() def get(self, section: str, option: str): self._load() try: option = self.parser.get(section, option) except NoOptionError: option = "" except NoSectionError: option = "" return option