解析ini
import configparser
def write_to_ini():
'''
写入ini
'''
config = configparser.ConfigParser()
config["mysql"] = {"host":"127.0.0.1",
"post":"8080"}
config["admininfo"] = {"username":"shitou",
"password":"sZs123456"}
#修改/添加键值对
config.set("admininfo", "age", "26")
with open("config.ini", "w") as configfile:
config.write(configfile)
def read_ini():
'''
读取ini内容
'''
config = configparser.ConfigParser()
config.read("config.ini", encoding="utf8")
#获取所有数据段组名
section_list = config.sections()
print(section_list) #['mysql', 'admininfo']
#判断是否存在数据
if config.has_section("admininfo"):
#获取一组的所有数据
admin_info = config.items("admininfo")
print(admin_info)
#[('username', 'shitou'), ('password', '123456')]
#h获取一组数据所有键
admin_info_key = config.options("admininfo")
print(admin_info_key) #['username', 'password']
#获取一组数据中的指定字段
admin_user = config.get("admininfo", "username")
print(admin_user) #shitou
admin_user = config["admininfo"]["username"]
print(admin_user) #shitou
def update_ini():
config = configparser.ConfigParser()
config.read("config.ini", encoding="utf8")
if config.has_option("admininfo", "age"):
config.set("admininfo", "age", "28")
with open("config.ini", "r+") as configfile: #r+
config.write(configfile)
def delete_ini_data():
config = configparser.ConfigParser()
config.read("config.ini", encoding="utf8")
#删除key
config.remove_option("admininfo", "age")
#删除整组数据
config.remove_section("admininfo")
with open("config.ini", "w") as configfile: #w
config.write(configfile)
#注意,若要区分大小写,可以修改
C:\Program Files\Python37\Lib\configparser:Line874:
#return optionstr.lower() -->return optionstr