先看实例:
#配置文档
[DATABASE]
data_address = ./data/
report_address = ./report/
[HTTP]
base_url = http://xxx.xx
import os
import configparser
# 获取当前py文件地址
proDir = os.path.split(os.path.realpath(__file__))[0]
# 组合config文件地址
configPath = os.path.join(proDir,"config.ini")
class ReadConfig:
def __init__(self):
#获取当前路径下的配置文件
self.cf = configparser.ConfigParser()
self.cf.read(configPath)
def get_config(self,field,key):
#获取配置文件中的key值
result = self.cf.get(field,key)
return result
def set_config(self,field,key,value):
#向配置文件中写入配置信息
fb = open(configPath,'w')
self.cf.set(field,key,value)
self.cf.write(fb)
===========================================
简介
ConfigParser模块在python中是用来读取配置文件,配置文件的格式跟windows下的ini
配置文件相似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
使用的配置文件的好处就是不用再程序中硬编码,可以是你的程序变得灵活起来。
注意:在python 3 中ConfigParser
模块名已更名为configparser
安装
函数
1,读取配置文件
(1)read(filename) 直接读取ini文件内容
(2)sections() 得到所有的section,并以列表的形式返回
(3)options(section) 得到该section的所有option
(4)items(section) 得到该section的所有键值对
(5)get(section,option) 得到section中option的值,返回为string类型
(6)getint(section,option) 得到section中option的值,返回为int类型
(7)getfloat(section,option)得到section中option的值,返回为float类型
(8)getboolean(section, option)得到section中option的值,返回为boolean类型
2,写入配置文件
(1)add_section(section) 添加一个新的section
(2)has_section(section) 判断是否有section
(3)set( section, option, value) 对section中的option进行设置
(4)remove_setion(section)删除一个section
(5)remove_option(section, option)删除section中的option
(6)write(fileobject)将内容写入配置文件。
属性文件格式(dbconfig.ini)
#数据库参数
[dbserver]
ip=192.20.101.100
port=3306
user=root
password=123456
dbname=mydb
注意:也可以使用:
替换=
代码
#python3
#author:lizm
#date:2018-01-31
'''
demo:ConfigParser使用
'''
import configparser
import sys
#获取属性文件的值
def dbconfig():
#生成config对象
cfg = configparser.ConfigParser()
#用config对象读取配置文件
cfg.read("dbconfig.ini")
#以列表形式返回所有的section
sections = cfg.sections()
print('sections:', sections)
#输出:sections: ['dbserver']
#得到指定section的所有option
options = cfg.options("dbserver")
print('options:', options)
#输出:options: ['ip', 'port', 'user', 'password', 'dbname']
#得到指定section的所有键值对
useritem = (cfg.items("dbserver"))
print('user:', useritem)
#输出:user: [('ip', '192.20.101.100'), ('port', '3306'), ('user', 'root'), ('password', '123456'), ('dbname', 'mydb')]
#指定section,option读取值
ip = cfg.get("dbserver", "ip")
port = cfg.get("dbserver", "port")
user = cfg.get("dbserver", "user")
password = cfg.get("dbserver", "password")
dbname = cfg.get("dbserver", "dbname")
return (ip,port,user,password,dbname)
def writeConfig():
cfg = configparser.ConfigParser()
#用config对象读取配置文件
cfg.read("dbconfig.ini")
#更新指定section,option的值
cfg.set("dbserver", "ip", "192.25.103.150")
#写入指定section增加新option和值
cfg.set("dbserver", "tablenmae", "py_table")
#增加新的section
cfg.add_section('dbserver2')
cfg.set('dbserver2', 'ip', '192.25.105.100')
#写回配置文件
cfg.write(open("dbconfig.ini", "w"))
if __name__ == '__main__':
dbconfig = dbconfig()
vrg_ip=dbconfig[0]
vrg_port=dbconfig[1]
vrg_user=dbconfig[2]
vrg_password=dbconfig[3]
vrg_dbname=dbconfig[4]
writeConfig()
注意:用python命令执行测试py:
方法一:切换到py所在的目录再执行python命令,正常
![]()
方法二:不切换目录直接执行python命令,异常:属性文件的[dbserver]不存在
![]()
原因:没有切到py所在的目录,没有找到正确的属性文件,导致异常;
解决方案:
#用config对象读取配置文件
cfg.read("dbconfig.ini")
#改为
#用config对象读取配置文件
#获取当前文件的目录
path_ = sys.path[0]
cfg.read(path_+"\dbconfig.ini")