python读取配置文件

import configparser  #实现插值的ConfigParser。
import codecs #编解码器——Python编解码器注册表、API和帮助程序。

class MyConfig(object): #定义一个对象
path = './'
def __init__(self, name):
self.config = configparser.ConfigParser() # 对象
self.name = name
self.config.read(name, encoding='utf-8') #对文件
def addSection(self, section): #添加节点
self.config.add_section(section)
def set(self, section, key, value): #设置配置文件
try:
self.config.add_section(section)
except Exception as e:
print(e)
self.config.set(section, key, value) #设置节点键和值

self.config.write(codecs.open(self.name, 'w', 'utf-8'))# 以utf-8格式打开

def get(self, section, key, default): #读取文件
try:
value = self.config.get(section, key)
except Exception as e:
print(e)
value = default
return value

gConfigs = {} #全局
def config_setPath(path):
MyConfig.path = path #类属性


def clearConfigs():
gConfigs.clear()

def config_set(strName, section, key, value):
name = MyConfig.path + strName
if name not in gConfigs:
gConfigs[name] = MyConfig(name + '.ini') #配置对象
gConfigs[name].set(section, key, value)


def config_get(strName, section, key, defaultValue): #获取配置

name = MyConfig.path + strName
gConfigs[name] = MyConfig(name + '.ini')
return gConfigs[name].get(section, key, defaultValue)

if __name__=='__main__':
pass
posted @ 2020-02-05 09:11  countryboy666  阅读(866)  评论(0编辑  收藏  举报