一、conf.ini文件输写格式:文件名:***.ini(固定格式),
[节点]
选项 = 选项值
[database] -->节点section username = admin --> #选项option :username, 选项值value: admin passwd = admin123 [path] logs = /Users/vv/PycharmProjects/untitled3.9/logs
二、获取节点及选项以及修改删除节点及选项
import configparser conf = configparser.ConfigParser() conf.read(filenames="conf.ini") #获取所有节点 sections = conf.sections() print(sections) #获取某节点下所有的选项 opthions = conf.options('path') print(opthions) #获取某节点下的某个选项 path = conf.get(section='path',option='logs_path') print(path) #获取某个节点下所有的选项及选项值(获取元组列表) data = conf.items(section='back_ground_database') #添加节点(有相同节点时会报错,因此需判断) add_section = 'test' if add_section not in sections: conf.add_section(section=add_section) #添加某节点下的选项及选项值 add_option = conf.set(section='test',option='name',value='vv') print(conf.items(section='test')) with open('conf.ini','w+') as file: conf.write(file) #移除节点 del_section = 'test' if del_section in sections: conf.remove_section(section=del_section) with open('conf.ini','w+') as file: conf.write(file) #移除节点下的选项 conf.remove_option(section='test',option='name') with open('conf.ini','w+') as file: conf.write(file)