配置文件try.ini内容:
[mysql]
db_host = 127.0.0.1
db_port = 3306
db_user = root
db_pass = password
[个人信息]
name = 飞飞
age = 30
address = 重庆沙坪坝
tel = 13900000000
[add]
add1 = 添加字符串
add2 = 再添加字符串
[del]
del1 = 删除字符串
del2 = 删除字符串2
[dele]
dele1 = dele1的值
dele2 = dele2的值
操作配置文件的操作代码:
#encoding=utf-8
import configparser
import os
cf = configparser.ConfigParser()
tryPath = os.path.dirname(os.path.abspath(__file__))+"\\try.ini"
# cf.read("try.ini",encoding="utf-8")
cf.read(tryPath,encoding="utf-8")
s = cf.sections() #
o = cf.options("mysql")
i = cf.items("mysql")
print ("sections:",s,"\noptions:",o,"\nitems:",i)
# 打印出的内容:
# sections: ['mysql', '个人信息', 'add', 'del', 'dele']
# options: ['db_host', 'db_port', 'db_user', 'db_pass']
# items: [('db_host', '127.0.0.1'), ('db_port', '3306'), ('db_user', 'root'), ('db_pass', 'password')]
print("*"*100)
cf.add_section("defineBySelf")
print ("sections:",cf.sections())
# sections: ['mysql', '个人信息', 'add', 'del', 'dele', 'defineBySelf']
cf.set("defineBySelf","name","qiaoqiao")
cf.set("defineBySelf","sex","girl")
print("optionOfSelf:",cf.items("defineBySelf"))
# sections: ['mysql', '个人信息', 'add', 'del', 'dele', 'defineBySelf']
print("*"*100)
print(cf.get("mysql","db_host"))
# 127.0.0.1