python config.ini的应用

  config.ini文件的结构是以下这样的:结构是"[ ]"之下是一个section,一部分一部分的结构。以下有三个section,分别为section0,section1,section2

[mysql config]
host=127.0.0.1
port=8080
username=root
password=123456

[online config]
online=www.online.com
username=peixm
password=123qwe


[test config]
test=www.test.com
username=peixm
password=123qwe

那么,怎么在代码中获取到这些内容呢?

首先,要有一个config.ini文件,我的目录结构是以下这样:

#!/usr/bin/env/python
# -*-coding:utf-8-*-
# authour:xiapmin_pei


import configparser,os

#封装一个路径,直接输入文件名称filename就可以获得filename的路径
def getPath(filename):
    return os.path.join(os.path.dirname(__file__),os.pardir,'data',filename)


class Config(object):

    def __init__(self,filename,section):
        """
        :param filename: 文件名称
        :param section: 属于文件中的第几个section,这是整形
        """
        self.section = section
        #实例化一个configparser对象
        self.cf = configparser.ConfigParser()
        #读取文件的内容
        self.cf.read(getPath(filename))

    def getconfig(self,avg):
        """
        获得想要属性的内容
        :param avg: 属性名称
        :return: 属性的值
        """
        print self.cf.sections()
        parameter =self.cf.get(self.cf.sections()[self.section],avg)
        return parameter


if __name__=="__main__":
    #实例化Config,想要config.ini文件,第2个section的内容
    con = Config("config.ini",1)
    #获取online这个属性的值
    print con.getconfig('online')

执行结果:由此可见,sections是一个列表

['mysql config', 'online config', 'test config']
www.online.com

Process finished with exit code 0

原文地址:https://www.cnblogs.com/peiminer/p/9415718.html