# 创建一个ini文件,存储链接DB的方式 [mbloan-test] host = 1xx.xx.xx.xx port = 3xx2 db = DBName username = username password = password # 创建py文件,编写代码读取ini文件 import os from configparser import ConfigParser
# 获取要读取的ini文件的路径 from testercenter.database import db_config_path class ReadConfig():
## dbsection 要与db.ini中的section(mbloan-test)保持一致
def __init__(self,dbsection):
cfg = ConfigParser()
# os.path.join(111,222)方法是将方法的传参以/符号拼接起来,拼接成路径 cfg.read(os.path.join(db_config_path,'db.ini')) self.section = dbsection self.host = cfg.get(self.section,'host') self.port = cfg.get(self.section,'port') self.db = cfg.get(self.section,'db') self.username = cfg.get(self.section,'username') self.password = cfg.get(self.section,'password')
方式2:ini文件的路径直接写死
# -*- coding: utf-8 -*- # Author:lucky,time:2019-06-10 import ConfigParser
#ini文件当前的路径 cfg1 = "test_cfg.ini" conf = ConfigParser.ConfigParser() conf.read(cfg1) #读取ini文件中的内容
# email参数为ini文件内的section字段,smtp_server为section下面的字段 print conf.get("email","smtp_server") print conf.get("Account information","username") print conf.items("Account information") #获取到Account information中的所有内容,返回字典类型 print conf.options("Account information") #获取到Account information中的变量名 #向ini中添加内容 print conf.add_section("Account") print conf.set("Account","title","1") print conf.write(open("test_cfg.ini","w+")) #向ini中修改内容 conf.set("Account","title","6") conf.write(open("test_cfg.ini","w+"))