• ini 文件读取操作


    1、创建ini文件,如(db_config.ini)

      内容如下(自己本地的数据库):

    [mysql]
    host=127.0.0.1
    port=3306
    user=root
    password=*******
    db_name=guest
    # user/password/db_name 根据自己设置填写即可

    2、ini 文件的读取

      创建读取operateConf.py 文件读取配置信息

      2.1、如果 db_config.ini 和 operateConf.py 文件在同一目录下

    import configparser    # 导库
    
    conf = configparser.ConfigParser()
    conf.read('db_config.ini')    # 读取 ini 文件
    
    host = conf.get('mysql','host')    # 获取host
    port = conf.get('mysql','port')    # 获取端口号
    user = conf.get('mysql','user')    # 获取用户名
    password = conf.get('mysql','password ')    # 获取密码
    db = conf.get('mysql','db_name')    # 获取数据库的名称

      2.2、如果 db_config.ini 和 operateConf.py 文件不在同一目录下---通过os来获取目录,拼接目录

    如下为我的目录结构

     

    import configparser
    import os
    
    os.path.dirname(__file__)    目录结构为 ../pyrequest/db_fixture/
    os.path.dirname(os.path.dirname(__file__))    目录结构为 ../pyrequest/
    base_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'db_config.ini')    文件目录为 ..../pyrequest/db_config.ini
    
    conf = configparser.ConfigParser()
    conf.read(base_dir)
    
    host = conf.get('mysql','host')
    port = conf.get('mysql','port')
    user = conf.get('mysql','user')
    password = conf.get('mysql','password ')
    db = conf.get('mysql','db_name')
    

      

      2.3、总结

    import configparser
    import os
    
    def base_dir(filename=None):
        ''' 获取文件路径'''
         return os.path.join(os.path.dirname(__file__),filename)
    
    def getLinux(name='mysql'):
         ''' 1.实例化类
             2.对文件进行读取
         '''
         lst = []
         conf = configparser.ConfigParser()
         config.read(base_dir('db_config.ini'))
    
         host = conf.get('mysql','host')
         port = conf.get('mysql','port')
         user = conf.get('mysql','user')
         password = conf.get('mysql','password ')
         db = conf.get('mysql','db_name')
    
         lst.append(host)    # 将元素加入列表中
         lst.append(port)
         lst.append(user)
         lst.append(password)
         lst.append(db)
    
         return lst
    
     getLinux()    # 调用函数
    

      

        

          

    
    
    
  • 相关阅读:
    ContentProvider简单介绍
    hdu 1087 Super Jumping! Jumping! Jumping!(dp 最长上升子序列和)
    点点文刊 -- 记录生活的色彩
    【struts2+hibernate4】小型电子商务站点
    IOS学习之蓝牙4.0
    POJ 1988 Cube Stacking (种类并查集)
    Android开发之 shape的使用
    妄想性仮想人格障害 新手教程 +改动器
    Spring 的 ApplicationEvent and ApplicationListener
    Offer是否具有法律效力?
  • 原文地址:https://www.cnblogs.com/siyu0123/p/12822603.html
Copyright © 2020-2023  润新知