简体   繁体   中英

Python: Read all config values from .ini file and store in Dictionary and access in other files

I have a config.ini file. When my python application starts, I want to read all config values and store them in a dictionary. Then this dictionary should be available in all other files

[sql]
Server=localhost
UserId=root
[url]
url1=localhost
UserId1=root

I have a Class1.py:

from configparser import SafeConfigParser

class class1(object):

    def __init__(self, *file_name):
        parser = SafeConfigParser()
        parser.read('config.ini')

        self.__config__ = {}
        for section in parser.sections():
            self.__dict__.update(parser.items(section)) 

configData= class1('config.ini')

In my main file, I am not able to access configData.Server

from class1 import configData print(configData.Server)

Strangely, the config keys are automatically getting converted to lowercase. Even my key is Server , it is getting changed to server .

So while configData.Server throws error configData.server works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM