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配置文件代码如下:

 1 import configparser
 2 
 3 class cconfigparser(object):
 4     def __init__(self,conf_path):
 5         self.fpath = conf_path
 6         self.cf = configparser.ConfigParser()
 7         self.cf.read(self.fpath,encoding='UTF-8')
 8 
 9     def write(self):
10         filename = open(self.fpath,'w')
11         self.cf.write(filename)
12         filename.close()
13 
14     # 添加指定的节点
15     def add_section(self,section):
16          sections = self.cf.sections()
17          if section in sections:
18              return
19          else:
20              self.cf.add_section(section)
21 
22     # 删除节点
23     def remove_section(self,section):
24         return self.cf.remove_section(section)
25 
26     #返回文件中的所有sections
27     def sections(self):
28         return self.cf.sections()
29 
30     # 获取节点下option对应的value值
31     def get(self,section,option):
32         return self.cf.get(section,option)
33 
34     # 在指定的section下添加option和value值
35     def set(self,section,option,value):
36         if self.cf.has_section(section):
37             self.cf.set(section,option,value)
38 
39     #移除指定section点内的option
40     def remove_option(self,section,option):
41         if self.cf.has_section(section):
42             resutl = self.cf.remove_option(section,option)
43             return resutl
44         return False
45 
46     # 返回section内所有的option和value列表
47     def items(self,section):
48         return self.cf.items(section)
49 
50     # 返回section所有的option
51     def options(self,section):
52         return self.cf.options(section)

猜你喜欢

转载自www.cnblogs.com/jiyanjiao-702521/p/9420343.html