zoukankan      html  css  js  c++  java
  • 读取 ini 配置文件

    ini 配置文件格式:db_config.ini

    '''
    [section]
    option=value
    '''
    [DATABASE1]
    host=192.168.30.80
    port=3306
    user=testacc
    passwd=test1234
    db=testdb
    charset=utf_8
    
    [DATABASE2]
    host=192.168.30.80
    port=3306

    (1)首先安装 configparser 类:一般标准库中都自带的,若无,则可 直接运行 pip install configparser 

    (2)使用这个类读取文件

    基本会使用到的一些函数:

    -read(filename) 直接读取文件内容
    -sections() 得到所有的section,并以列表的形式返回
    -options(section) 得到该section的所有option,并以列表的形式返回
    -items(section) 得到该section的所有键值对,并以列表的形式返回
    -get(section,option) 得到section中option的值,返回为string类型
    -getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

    #简单的读取
    from
    configparser import ConfigParser conf=ConfigParser() conf.read('E:PyCharm 2017.2.4Interfacedb_config.ini')
    print(conf.sections())
    print(conf.options(
    'DATABASE1'))
    print(conf.items(
    'DATABASE1'))


    #输出结果

    ['DATABASE1', 'DATABASE2']
    ['host', 'port', 'user', 'passwd', 'db', 'charset']
    [('host', '192.168.30.80'), ('port', '3306'), ('user', 'testacc'), ('passwd', 'test1234'), ('db', 'testdb'), ('charset', 'utf_8')]

    #进行了简单的封装,其他地方可进行引用
    #read_db_conig.py
    from
    configparser import ConfigParser file='E:PyCharm 2017.2.4Interfacedb_config.ini' conf=ConfigParser() conf.read(file) def getHostValue(): host= conf.get('DATABASE1', 'host') return host def getPortValue(): port=conf.get('DATABASE1','port') return port if __name__=='__main__': host=getHostValue() print(host)
  • 相关阅读:
    sql相关操作
    web前端技术归类
    在EasyUI中统一判断是否有选中行,如果有则将选中行数据传入回调函数
    几种不同的分页处理办法
    将json格式日期(毫秒数)转成日常日期格式和日常格式时间对比
    在asp.net中导出表格Excel数据
    生成html文件
    EasyUI时间格式化
    checkbox,radio,selected相关操作
    javascript生成n至m的随机整数
  • 原文地址:https://www.cnblogs.com/cxx1/p/8677800.html
Copyright © 2011-2022 走看看