1.简介
- read(filename) 读取ini文件内容
- sections() 以列表形式展示所有的section
- options(section) 展示该section的option
- items(section) 得到该section的所有键值对
- get(section,option) 得到section中option的值,返回为string类型
- getint(section,option) 得到section中option的值,返回int类型,还有相应的getboolean()和getfloat()函数。
2.动态写入配置文件
- add_section(section) 添加一个新的section
- set(section,option,value) 新增section中的option
def writeIni():
# 第一步:创建conf对象
conf = configparser.ConfigParser()
# 第二步:添加section、options的值
conf.add_section("path")
conf.set("path", "back_dir", "/Users/abc/PycharmProjects/Pythoncoding/projects/") # option
conf.set("path", "target_dir", "/Users/abc/PycharmProjects/Pythoncoding/") # option
conf.add_section("file")
conf.set("file", "back_file", "apitest")
conf.set("file", "num", "10")
# 第三步:写入文件
with open("path.ini", 'w')as conffile:
conf.write(conffile)
执行以上代码,写入配置文件,生成一个path.ini配置文件:
[path]
back_dir = /Users/abc/PycharmProjects/Pythoncoding/projects/
target_dir = /Users/abc/PycharmProjects/Pythoncoding/
[file]
back_file = apitest
num = 10
读取配置文件:
def readIni():
config = configparser.ConfigParser()
# 第四步:读取配置文件中的section、options的值
# config.read_file(open('path.ini'))
# 一开始是用上面的read_file读取配置文件的,但是配置文件里有中文
# 读取了之后出现编码问题,运行出错,故用下面的read函数读取
config.read('path.ini', encoding='UTF-8')
back_dir = config.get('path', 'back_dir')
back_file = config.get("file", "back_file")
num = config.get("file", "num")
target_dir = config.get("path", "target_dir")
l1 = config.sections()
print("back_dir = %s" % back_dir)
print("back_file = %s" % back_file)
print("num = %s" % num)
print("target_dir = %s" % target_dir)
print("l1 = %s" % l1)
i = config.getint("file", "num")
print("i = %s" % i)
l2 = config.options("file")
print("l2 = %s" % l2)
l3 = config.items("file")
print("l3 = %s" % l3)
""" 输出如下:
back_dir = /Users/abc/PycharmProjects/Pythoncoding/projects/
back_file = apitest
num = 10
target_dir = /Users/abc/PycharmProjects/Pythoncoding/
l1 = ['path', 'file']
i = 10
l2 = ['back_file', 'num']
l3 = [('back_file', 'apitest'), ('num', '10')]
"""
删除section和option操作操作:
def remove_section():
conf_path = "path.ini"
config = configparser.ConfigParser()
config.read(conf_path, encoding='UTF-8')
# 删除section是section1里md5选项
config.remove_option('section1', 'md5')
# 删除section是section2里所有选项
config.remove_section('section2')
# 删除后必须写入文件才有效
with open(conf_path, 'w', encoding="UTF-8")as file:
config.write(file)