# coding=utf-8 import configparser import os # 实例化ConfigParser对象 config = configparser.ConfigParser() # 读取文件内容 PATH = os.getcwd() config_file = rf'{PATH}config.ini' config.clear() # 读取前清除已读内容。在读取多个文件内容时,若不清除,会出现非预期内容。 config.read(config_file) # 新增section section = "login" if not config.has_section(section): config.add_section(section) # 新增一个section"login",若section"login"存在,则会报错"Section 'login' already exists" # 新增/修改配置文件的键值 config.set(section, 'username', '1111') config.set(section, 'password', '2222') config.set(section, 'username', '3333') with open(config_file, 'w') as configfile: config.write(configfile) # 读取配置文件键值 username = config.get('login', 'username') password = config.get('login', 'password') print(username, password) null_section = config.get('login4', 'username', fallback=u'section 不存在') # 若section或option不存在,fallback返回后备值 null_option = config.get('login4', 'nullOption', fallback=u'option 不存在') print(null_section, null_option) # 另一种方式读取配置文件键值 section_object = config["login"] # 生成一个section对象 username = section_object["username"] # 像dict一样读取username的值 print(section_object, username) # 获取配置文件所有section sections = config.sections() print(sections) # 获取对应section下可用的键 keys = config.options('login') print(keys) # has_section()方法判断section是否存在,存在返回True,不存在返回False test1 = config.has_section('login') test2 = config.has_section('test') print(test1, test2) # has_option()方法判断指定section下,某个键是否存在,存在返回True,不存在返回False test1 = config.has_option('login', 'username') test2 = config.has_option('login', 'pwd') print(test1, test2) # 删除某个section下的键 config.remove_option('login', 'username') # 删除某个section config.remove_section('login1') # 删除操作只删除了内存信息,需要"w"操作保存删除操作 with open(config_file, 'w') as configfile: config.write(configfile) # 暂时没有读取出dict格式的配置文件信息的方法,需要自己处理 config = configparser.ConfigParser() PATH = os.getcwd() config_file = rf'{PATH}config.ini' config.read(config_file) loginParam = config['login2'] param_dict = {} loginParam_dict = dict(loginParam.items()) # 将loginParam_dict 添加到param_dict中,使用该方法可以将多个section中的信息添加到一个变量中 param_dict.update(loginParam_dict) # for key, value in loginParam.items(): # paramDict[key] = value # print(paramDict)