configparser模块
api:
sections() 返回所有配置节名称,sans默认。 has_section(section) Return whether the given section exists. has_option(section, option) 返回给定option是否存在于给定的section。 options(section) 返回指定section的配置选项列表。 read(filenames, encoding=None) 读取并解析指定的配置文件列表。 的名字。还允许使用单个文件名。不存在的文件 将被忽略。返回成功读取文件的列表。 read_file(f, filename=None) 读取并解析一个配置文件,作为一个文件对象。 文件名默认为f;它只用于错误。 消息(如果f没有' name'属性,使用字符串' <???>) read_string(string) 从给定的字符串读取配置。 read_dict(dictionary) Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. get(section, option, raw=False, vars=None, fallback=_UNSET) 返回指定选项的字符串值。所有%篡改 根据传入的默认值,在返回值中展开。 构造函数和默认部分。额外的替换可能是 使用“vars”参数,它必须是一个字典。 内容覆盖任何预先存在的默认值。如果“选项”是关键字。 “vars”,“vars”的值被使用。 getint(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to an integer. getfloat(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to a float. getboolean(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to a boolean (currently case insensitively defined as 0, false, no, off for False, and 1, true, yes, on for True). Returns False or True. items(section=_UNSET, raw=False, vars=None) 如果给定section,则返回一个包含(名称、值)的元组列表。 本节中的每个选项。否则,返回一个元组列表。 (section_name, section_proxy)用于每个部分,包括DEFAULTSECT。 remove_section(section) Remove the given file section and all its options. remove_option(section, option) Remove the given option from the given section. set(section, option, value) Set the given option. write(fp, space_around_delimiters=True) 写入配置状态。ini格式。如果 “space_around_delimiters”是True(默认),分隔符。 键和值之间被空格包围。
operate:
#!/usr/bin/env python # -*- encoding:utf-8 -*- import configparser cf = configparser.ConfigParser() cf.read('test.conf', encoding='utf-8') # return list secs = cf.sections() print(secs, type(secs)) # 获取内容 str1 = cf.get('sec_a', 'k1') print(str1) # 添加内容 cf.add_section("sec_c") cf.set("sec_c", "name", "jove") cf.set("sec_c", "age", "21") # 删除选项 cf.remove_option("sec_c","name") # 删除section cf.remove_section("sec_c") # 重新写入文件 cf.write(open('test.conf', 'w', encoding='utf-8'))
浙公网安备 33010602011771号