这篇博客我主要想总结一下python中的ini文件的使用,最近在写python操作mysql数据库,那么作为测试人员测试的环境包括(测试环境,UAT环境,生产环境)每次需要连接数据库的ip,端口,都会不同,那么如何方便的来修改这些内容,就想到了配置文件,接下来我们就了解一下python中的配置文件ini吧
ini配置文件常被用作存储程序中的一些参数,通过它,可以将经常需要改变的参数保存起来
ini文件分为两个部分,一部分是section,一部分是key,value
格式就是:
[section1]
Key1=value1
Key2=value2
[section2]
Key1 =value1
Key2 = value2
在说一个一会代码中用到的一个函数__del__()函数(但是在我如下代码中未实现,目前仍在研究中,所以在本代码中写了write()方法代替,每次在ini中增加或者删除操作都要调用write()方法,这样才会把数据同步到本地的ini文件中,我会后续继续研究del的方法)
a) 创建对象后,python解释器会自动调用__ini__()方法,当删除一个对象时,python的解释器也会自动调用一个方法__del__(),在python中对于开发者来说很少会直接销毁对象,如果需要应该使用__del__(方法)
b) 当一个对象的引用数为0的时候,会自动调用__del__()方法,也就是说当对象引用执行完后python会自动调用__del__()函数
Python中操作ini配置文件代码如下:
1 importconfigparser2
3 classcconfigparser(object):4 def __init__(self,conf_path):5 self.fpath =conf_path6 self.cf =configparser.ConfigParser()7 self.cf.read(self.fpath,encoding='UTF-8')8
9 defwrite(self):10 filename = open(self.fpath,'w')11 self.cf.write(filename)12 filename.close()13
14 #添加指定的节点
15 defadd_section(self,section):16 sections =self.cf.sections()17 if section insections:18 return
19 else:20 self.cf.add_section(section)21
22 #删除节点
23 defremove_section(self,section):24 returnself.cf.remove_section(section)25
26 #返回文件中的所有sections
27 defsections(self):28 returnself.cf.sections()29
30 #获取节点下option对应的value值
31 defget(self,section,option):32 returnself.cf.get(section,option)33
34 #在指定的section下添加option和value值
35 defset(self,section,option,value):36 ifself.cf.has_section(section):37 self.cf.set(section,option,value)38
39 #移除指定section点内的option
40 defremove_option(self,section,option):41 ifself.cf.has_section(section):42 resutl =self.cf.remove_option(section,option)43 returnresutl44 returnFalse45
46 #返回section内所有的option和value列表
47 defitems(self,section):48 returnself.cf.items(section)49
50 #返回section所有的option
51 defoptions(self,section):52 return self.cf.options(section)