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.int')

    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.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')

    

      

 

猜你喜欢

转载自www.cnblogs.com/siyu0123/p/12822603.html