Python-全局配置文件(conf.ini)的读取与写入

时间:2021-08-03
本文章向大家介绍Python-全局配置文件(conf.ini)的读取与写入,主要包括Python-全局配置文件(conf.ini)的读取与写入使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、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)
三十六般武艺,七十二般变化,修练出个人品牌并发出光芒

原文地址:https://www.cnblogs.com/deeptester-vv/p/15093619.html