配置文件如下
config_data.ini
[database]
password = 123456
[host]
ip = 127.0.0.1
[mysql]
username = zale
password = 123456
pord = 8080s
首先导入configparser模块
代码实现如下:
import configparser
import os
#读取
cf=configparser.ConfigParser()
# read(filename) 读文件内容
files=cf.read("config_data.ini")
print(files)
sec=cf.sections()#得到所有的section,以列表形式返回
print(sec)
#得到section下的所有option
opt=cf.options("mysql")
print(opt)
# items 得到section的所有键值对
value=cf.items("mysql")
print(value)
# get(section,option) 得到section中的option值,返回string/int类型的结果
mysql_user=cf.get("database","username")
mysql_password=cf.get("database","password")
#得到section中option的值,返回int类型的结果
mysql_password1=cf.getint("database","password")
print(mysql_user)
print(mysql_password)
print(mysql_password1)
#写入
# # add section 添加section项
cf.add_section("EMAIL")
# # set(section,option,value) 给section项中写入键值对
cf.set("EMAIL", "user", "laozhang")
with open("config_data.ini","w+") as f:
cf.write(f)
#删除
# remove_section(section) 删除某个section的数值
cf.remove_section("EMAIL")
# remove_option(section,option) 删除某个section下的option的数值
cf.remove_option("database","username")
with open("config_data.ini","w+") as f:
cf.write(f)
输出结果
['config_data.ini']
['database', 'host', 'mysql']
['username', 'password', 'pord']
[('username', 'zale'), ('password', '123456'), ('pord', '8080')]
zale
123456
123456