Python 标准库:configparser——配置文件解析

文章目录

  • 模块介绍
  • 使用场景
  • 主要类
  • 主要方法
  • – ConfigParser()
  • – read(filenames)
  • – get(section, option)
  • – getint(section, option)
  • – getfloat(section, option)
  • – getboolean(section, option)
  • – set(section, option, value)
  • – add_section(section)
  • – remove_section(section)
  • – remove_option(section, option)
  • – write(file)
  • – sections()
  • – options(section)
  • – items(section)
  • – has_section(section)
  • – has_option(section, option)
  • – read_file(file)
  • – read_dict(dictionary)
  • 注意事项
  • 总结

  • 模块介绍

    configparser 是 Python 标准库中的一个模块,用于读取、解析和写入 .ini 格式的配置文件。.ini 文件通常采用键值对的形式来组织配置信息,并将这些配置信息分组到不同的节(sections)中。这个模块提供了简单的接口来管理应用程序的配置,特别适用于小型或中型项目中的配置文件管理。

    configparser 模块支持读取、修改和创建新的配置文件,且能方便地进行节的增删操作。它的行为类似于 Windows 平台上传统的 .ini 配置文件格式,但也可以跨平台使用,适用于 Linux 和 macOS 等其他操作系统。

    使用场景

  • 应用程序的配置文件管理:用于存储应用的配置信息,如数据库连接字符串、文件路径、应用版本、日志设置等。
  • 用户设置:存储用户的偏好设置,例如 UI 配置、语言选择、主题等。
  • 跨平台应用程序:在不同操作系统中使用 .ini 格式存储和读取配置文件,确保配置文件格式的兼容性。
  • 插件系统:在插件系统中,可以使用 .ini 配置文件来指定插件的启用状态、设置或版本号等。
  • 环境配置:用于存储生产环境、开发环境和测试环境等不同环境下的配置信息。
  • 主要类

    类名 描述
    ConfigParser 这是 configparser 模块的核心类,负责读取、修改、删除 .ini 配置文件中的数据。

    主要方法

    函数 描述
    ConfigParser() 创建一个 ConfigParser 对象,用于读取、写入和修改配置文件。
    read(filenames) 读取一个或多个配置文件。文件可以是绝对路径或相对路径。
    get(section, option) 获取指定节(section)中的指定选项(option)的值。返回字符串类型。
    getint(section, option) 获取指定节中指定选项的值,并将其转换为整数类型。
    getfloat(section, option) 获取指定节中指定选项的值,并将其转换为浮动类型。
    getboolean(section, option) 获取指定节中指定选项的值,并将其转换为布尔值。
    set(section, option, value) 设置指定节中指定选项的值。
    add_section(section) 向配置文件中添加一个新节(section)。
    remove_section(section) 删除指定的节。
    remove_option(section, option) 删除指定节中的指定选项。
    write(file) 将当前的配置写入到文件对象中。
    sections() 返回所有节的名称列表。
    options(section) 返回指定节中的所有选项名。
    items(section) 返回指定节中的所有选项和值,以列表的形式返回。
    has_section(section) 检查是否存在指定的节
    has_option(section, option) 检查指定节是否包含指定的选项
    read_file(file) 从文件对象中读取配置(与 read() 类似,但接受一个文件对象而非文件名)
    read_dict(dictionary) 从字典读取配置

    有如下配置文件(config.ini):

    [general]
    version = 1.0
    author = John Doe
    
    [settings]
    max_connections = 100
    timeout = 30
    # timeout = 20
    
    [advanced]
    enabled = true
    new_feature = Enabled
    
    

    – ConfigParser()

    创建一个 ConfigParser 对象。

    import configparser
    
    # 创建 ConfigParser 对象
    config = configparser.ConfigParser()
    
    

    – read(filenames)

    读取一个或多个配置文件。

    import configparser
    
    # 创建 ConfigParser 对象
    config = configparser.ConfigParser()
    
    # 读取配置文件
    config.read('config.ini')
    
    

    – get(section, option)

    获取指定节和选项的值。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 获取 'general' 节下 'version' 选项的值
    version = config.get('general', 'version')
    print(f"Version: {version}")
    
    

    – getint(section, option)

    获取指定节中指定选项的值,并将其转换为整数类型。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 获取 'database' 节下 'port' 选项的值,并转换为整数
    timeout = config.getint('settings', 'timeout')
    print(f"timeout: {timeout}")
    
    
    

    – getfloat(section, option)

    获取指定节中指定选项的值,并将其转换为浮动类型。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 获取 'settings' 节下 'timeout' 选项的值,并转换为浮动类型
    timeout = config.getfloat('settings', 'timeout')
    print(f"Timeout: {timeout}")
    
    

    – getboolean(section, option)

    获取指定节中指定选项的值,并将其转换为布尔类型。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 获取 'advanced' 节下 'enabled' 选项的值,并转换为布尔值
    enabled = config.getboolean('advanced', 'enabled')
    print(f"Advanced features enabled: {enabled}")
    
    

    – set(section, option, value)

    设置指定节中指定选项的值。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 设置 'general' 节下 'version' 选项的值
    config.set('general', 'version', '2.0')
    
    # 将更新后的内容写回配置文件
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
        
    print(config.get('general', 'version'))
    
    

    – add_section(section)

    添加新的节(section)。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 如果没有 'new_section' 节,则添加
    if not config.has_section('new_section'):
        config.add_section('new_section')
    
    # 将更新后的内容写回配置文件
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
    

    – remove_section(section)

    删除指定的节。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 删除 'new_section' 节
    config.remove_section('new_section')
    
    # 将更新后的内容写回配置文件
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
    
    

    – remove_option(section, option)

    删除指定节中的指定选项。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 删除 'general' 节下的 'version' 选项
    config.remove_option('general', 'version')
    
    # 将更新后的内容写回配置文件
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
    

    – write(file)

    将当前的配置写入到文件对象中。

    import configparser
    
    config = configparser.ConfigParser()
    # 将配置写回到文件
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
    
    

    – sections()

    返回所有节的名称列表。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 获取所有节的名称
    sections = config.sections()
    print(f"Sections: {sections}")
    

    – options(section)

    返回指定节中的所有选项名。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 获取 'general' 节中的所有选项名
    options = config.options('general')
    print(f"Options in 'general' section: {options}")
    

    – items(section)

    返回指定节中的所有选项和值,结果为列表形式。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 获取 'general' 节中的所有选项和值
    items = config.items('general')
    print(f"Items in 'general' section: {items}")
    

    – has_section(section)

    检查是否存在指定的节。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 检查是否存在 'general' 节
    if config.has_section('general'):
        print("'general' section exists.")
    else:
        print("'general' section does not exist.")
    

    – has_option(section, option)

    检查指定节是否包含指定的选项。

    import configparser
    
    config = configparser.ConfigParser()
    # 读取配置文件
    config.read('config.ini')
    # 检查 'general' 节下是否存在 'version' 选项
    if config.has_option('general', 'version'):
        print("'version' option exists in 'general' section.")
    else:
        print("'version' option does not exist in 'general' section.")
    
    

    – read_file(file)

    从文件对象中读取配置(与 read() 类似,但接受一个文件对象而非文件名)。

    import configparser
    
    config = configparser.ConfigParser()
    with open('config.ini', 'r') as f:
        config.read_file(f)
    
    

    – read_dict(dictionary)

    从字典读取配置。

    import configparser
    
    # 创建 ConfigParser 对象
    config = configparser.ConfigParser()
    
    # 定义一个字典,包含配置内容
    config_dict = {
        'General': {
            'name': 'Alice',
            'age': '25'
        },
        'Settings': {
            'theme': 'dark',
            'language': 'English'
        }
    }
    
    # 使用 read_dict() 方法加载字典数据
    config.read_dict(config_dict)
    
    # 显示加载后的配置内容
    print("加载后的配置内容:")
    for section in config.sections():
        print(f"[{section}]")
        for option in config.options(section):
            print(f"{option} = {config.get(section, option)}")
    
    

    注意事项

  • 节名和选项名的大小写

  • ConfigParser 会将节名和选项名自动转换为小写。如果需要保留原始大小写,可以通过设置 optionxform 属性为 str 来禁用此行为。
  • 文件读写模式

  • config.read() 只能读取文件,不会修改原文件。要修改配置文件,需要使用 config.set() 方法进行更改,并使用 config.write() 方法将更改保存到文件中。
  • 类型转换

  • ConfigParser.get() 方法默认返回字符串类型。如果需要获取其他类型(例如整数、布尔值等),可以使用 getint()、getfloat() 和 getboolean() 方法。
  • 处理缺少的节或选项

  • 在访问配置项时,可能会遇到 NoSectionError 或 NoOptionError 异常。建议在访问之前检查节或选项是否存在,或者使用 config.has_section() 和 config.has_option() 方法进行判断。
  • 默认值

  • 可以为 ConfigParser 提供默认配置,通过 defaults 参数传递一个字典,或者在访问选项时提供默认值。如果指定的选项不存在,则返回默认值。
  • 文件格式注意

  • .ini 文件的注释行必须以 # 或 ; 开头,且注释行在文件读取时会被忽略。
  • 总结

    configparser 模块为 Python 提供了简洁而强大的配置文件管理功能,特别适合管理 .ini 格式的配置文件。它支持读取、修改和写入配置文件中的节、选项和值,且能处理类型转换、缺省值、节和选项的增删等常见需求。该模块是跨平台的,适用于各种操作系统。

    作者:骑个小蜗牛

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python 标准库:configparser——配置文件解析

    发表回复