Python 之configparser模块

一、示例

'''
添加
add_section(section)    向实例添加一个section
set(section, option, value)    如果给定的部分存在,将给定的选项设置为指定的值
optionxform(option)    也可以在一个实例上重新设置它,对于一个需要字符串参数的函数。例如,将其设置为str,将使选项名称区分大小写

查找
defaults()    返回包含实例范围默认值的字典。
sections()    返回可用的section的列表;默认section不包括在列表中
has_section(section)    指示指定的section是否出现在配置中。默认的section未被确认
options(section)    返回指定section中可用的选项列表。
has_option(section, option)    如果给定的section存在,并且包含给定的选项,则返回True;否则返回False
get(section, option)    为指定的section获取一个选项值。
getint(section, option)    它将指定section中的选项强制转换为整数
getfloat(section, option)    它将指定section中的选项强制转换为浮点型
getboolean(section, option)    强制转换为布尔型,”1”, “yes”, “true”, and “on”, 转换为True,”0”, “no”, “false”, and “off”, 转换为Falseo 其他返回ValueError.
items(section)    返回给定section中每个选项的(name,value)对的列表。

删除
remove_option(section, option)  从指定的部分中删除指定的选项。如果该部分不存在,请提出NoSectionError。如果存在的选项被删除,返回True;否则返回False。
remove_section(section) 从配置中删除指定的section。如果这个部分确实存在,返回True。否则返回假

判断是否存在
has_option(section, option)
has_section(section)
'''

import configparser

if __name__ == '__main__':
    config_file = configparser.ConfigParser()

    # 创建配置文件
    config_file.add_section("test")
    # 添加
    config_file.set("test", "username", "yy")
    config_file.set("test", "password", "123")
    config_file.set("test", "salt", "abc")
    #修改
    config_file["test"].update({"username": "yy1015"})
    #删除
    config_file.remove_option("test", "salt")
    with open("config.ini","w") as file_object:
        config_file.write(file_object)
    
    # 读取配置文件
    config_file.read('config.ini')
    print(config_file.get("test", "username"))
    print(config_file.has_option("test", "salt"))
    

 

posted @ 2022-10-17 09:03  样子2018  阅读(37)  评论(0编辑  收藏  举报