Python中操作ini配置文件

这篇博客我主要想总结一下python中的ini文件的使用,最近在写python操作mysql数据库,那么作为测试人员测试的环境包括(测试环境,UAT环境,生产环境)每次需要连接数据库的ip,端口,都会不同,那么如何方便的来修改这些内容,就想到了配置文件,接下来我们就了解一下python中的配置文件ini吧

  1. ini配置文件常被用作存储程序中的一些参数,通过它,可以将经常需要改变的参数保存起来
  2. ini文件分为两个部分,一部分是section,一部分是key,value
  3. 格式就是:

[section1]

Key1=value1

Key2=value2

[section2]

Key1 =value1

Key2 = value2

  1. 在说一个一会代码中用到的一个函数__del__()函数(但是在我如下代码中未实现,目前仍在研究中,所以在本代码中写了write()方法代替,每次在ini中增加或者删除操作都要调用write()方法,这样才会把数据同步到本地的ini文件中,我会后续继续研究del的方法)

a)     创建对象后,python解释器会自动调用__ini__()方法,当删除一个对象时,python的解释器也会自动调用一个方法__del__(),在python中对于开发者来说很少会直接销毁对象,如果需要应该使用__del__(方法)

b)     当一个对象的引用数为0的时候,会自动调用__del__()方法,也就是说当对象引用执行完后python会自动调用__del__()函数

Python中操作ini配置文件代码如下:

 import configparser

 class cconfigparser(object):
def __init__(self,conf_path):
self.fpath = conf_path
self.cf = configparser.ConfigParser()
self.cf.read(self.fpath,encoding='UTF-8') def write(self):
filename = open(self.fpath,'w')
self.cf.write(filename)
filename.close() # 添加指定的节点
def add_section(self,section):
sections = self.cf.sections()
if section in sections:
return
else:
self.cf.add_section(section) # 删除节点
def remove_section(self,section):
return self.cf.remove_section(section) #返回文件中的所有sections
def sections(self):
return self.cf.sections() # 获取节点下option对应的value值
def get(self,section,option):
return self.cf.get(section,option) # 在指定的section下添加option和value值
def set(self,section,option,value):
if self.cf.has_section(section):
self.cf.set(section,option,value) #移除指定section点内的option
def remove_option(self,section,option):
if self.cf.has_section(section):
resutl = self.cf.remove_option(section,option)
return resutl
return False # 返回section内所有的option和value列表
def items(self,section):
return self.cf.items(section) # 返回section所有的option
def options(self,section):
return self.cf.options(section)
上一篇:网页中模拟Excel电子表格实例分享


下一篇:Python 中 configparser 配置文件的读写及封装,配置文件存放数据,方便修改