python读写ini配置文件并修改

首先添加configparser库

import configparser

写一个ini配置文件

#创建一个管理对象
conf = configparser.ConfigParser()
#添加一个section
conf.add_section("section")  
#给section添加key和value,set也可以对已有的键值对进行覆盖修改
conf.set( "section", 'key', 'value') 
#保存该文件,注意一定不要漏掉这个
conf.write(open("filename.ini", "w", encoding="utf-8"))

看一下运行结果
在这里插入图片描述

读取ini配置文件

import configparser
conf = configparser.ConfigParser()
conf.read("filename.ini", encoding="utf-8") 
#按照section,key查找
key=conf.get("section","key")
print(key)

#找到所有section,返回的是一个列表
sections = conf.sections()
print(sections)

#找到section下的所有键值对,返回的是一个列表
items=conf.items("section")
print(items)

看一下运行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Destiny_xt/article/details/121169066