import configparser
import os
class rwini(object):
def __init__(self,filename):
self.filename = filename
self.abspath = os.path.dirname(os.path.realpath(__file__))
self.cfgpath = os.path.join(self.abspath, self.filename)
#读取 ini
def getFile(self):
item_list=[]
conf = configparser.ConfigParser()
conf.read(self.cfgpath, encoding='utf-8')
sections = conf.sections()
for section in sections:
items = conf.items(section)
item_list.append(items)
return item_list
#读取指定节点下的指定key的值
def appoint_sections_key(self,sect,key):
i=0
conf = configparser.ConfigParser()
conf.read(self.cfgpath, encoding='utf-8')
if sect in conf.sections():
for keys in conf.items(sect):
i+=1
if key in keys[0]:
return conf.items(sect)[i-1][-1]
else:
return "section is error"
#移除某一结点下的小节点
def remove_opt(self,sect,opt):
conf = configparser.ConfigParser()
conf.read(self.cfgpath, encoding='utf-8')
if sect in conf.sections():
for item in conf.items(sect):
if opt in item:
conf.remove_option(sect,opt)
with open(self.cfgpath, 'w', encoding='utf-8') as fp:
conf.write(fp)
else:
return 'error'
else:
return 'section is error'
#增加节点
def add_section(self,sect):
conf = configparser.ConfigParser()
conf.read(self.cfgpath, encoding='utf-8')
if sect in conf.sections():
return '{} already exists'.format(sect)
else:
conf.add_section(sect)
with open(self.cfgpath, 'w', encoding='utf-8') as fp:
conf.write(fp)
#增加小节点
def add_section_key_value(self,sect,key,value):
conf = configparser.ConfigParser()
conf.read(self.cfgpath, encoding='utf-8')
if sect in conf.sections():
conf.set(sect, key, value)
with open(self.cfgpath, 'w', encoding='utf-8') as fp:
conf.write(fp)
else:
return 'section is error'
#修改小节点
def mod_opt(self,sect,key,value):
self.add_section_key_value(sect,key,value)
ep=rwini('conf.ini')
# print(ep.getFile()) #[[('server', 'stmp@163.com'), ('port', '25')], [('sender', '张三'), ('phone', '123456')]]
print(ep.add_section('section3'))
ep.add_section_key_value('section3','name','hahah')
# ep.remove_opt('section3','name')
ep.mod_opt('section3','name','xixi')
print(ep.appoint_sections_key('section0','port'))
conf.ini
[section0]
server = stmp@163.com
port = 25
[section1]
sender = 张三
phone = 123456
[section3]
name = xixi