python toml配置文件的读取和写入

介绍

在 Python 中读取 TOML 配置文件非常便捷,主要有两种方式:

  • 使用 Python 3.11+ 内置的 tomllib 模块(推荐)

  • 使用第三方库 toml(兼容低版本 Python)

TOML 配置文件格式

详见链接:
https://www.malaoshi.top/show_1GW1lZnjqH1e.html

准备 TOML 配置文件

文件名:config.toml

内容如下:

# 应用基本配置
[app]
name = "MyApp"
version = "1.0.0"
debug = true

# 数据库配置
[database]
host = "localhost"
port = 5432
user = "admin"
password = "secret"
tables = ["users", "products"]

# 嵌套结构
[server]
address = "0.0.0.0"
port = 8080
timeout = 30.5
limits = { max_connections = 100, max_requests = 1000 }

使用 Python 3.11+ 内置的 tomllib

tomllib 是 Python 3.11 新增的标准库,专门用于解析 TOML 文件,无需额外安装依赖。

import tomllib  # Python 3.11+ 内置
import os

def read_toml_config(file_path: str) -> dict:
    """
    读取TOML配置文件并返回字典

    Args:
        file_path: TOML文件路径

    Returns:
        解析后的配置字典

    Raises:
        FileNotFoundError: 文件不存在时抛出
        ValueError: 解析失败时抛出
    """
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"配置文件不存在: {file_path}")

    # 注意:tomllib需要以二进制模式('rb')打开文件
    with open(file_path, "rb") as f:
        try:
            return tomllib.load(f)
        except tomllib.TOMLDecodeError as e:
            raise ValueError(f"TOML文件解析错误: {str(e)}")

# 使用示例
if __name__ == "__main__":
    try:
        config = read_toml_config("config.toml")

        # 访问配置项(解析后为嵌套字典)
        print(f"应用名称: {config['app']['name']}")
        print(f"数据库地址: {config['database']['host']}:{config['database']['port']}")
        print(f"服务器超时时间: {config['server']['timeout']}秒")
        print(f"最大连接数: {config['server']['limits']['max_connections']}")
        print(f"数据库表列表: {config['database']['tables']}")

    except Exception as e:
        print(f"错误: {e}")

使用第三方库 toml(兼容低版本 Python)

如果使用 Python 3.10 及以下版本,可安装第三方库 toml(功能与 tomllib 类似,但支持文本模式读取)。

安装依赖

pip install toml

读取代码

import toml  # 第三方库,需安装

# 读取方式1
def read_toml1(file_path: str) -> dict:
    """读取TOML配置文件(兼容Python 3.10及以下)"""
    # toml库支持文本模式('r')打开
    with open(file_path, "r", encoding="utf-8") as f:
        try:
            return toml.load(f) # 返回dict类型
        except toml.TomlDecodeError as e:
            raise ValueError(f"TOML文件解析错误: {str(e)}")

# 读取方式2
def read_toml2(file_path: str) -> dict:
    """读取TOML配置文件(兼容Python 3.10及以下)"""
    return toml.load(file_path) # 返回dict类型


# 使用示例
if __name__ == "__main__":
    try:
        # 返回dict类型
        config = read_toml1("api_keys.txt")
        print(config)
        # 访问配置项(与tomllib完全一致)
        print(f"调试模式: {config['app']['debug']}")
        print(f"数据库用户: {config['database']['user']}")
        print(f"服务器地址: {config['server']['address']}:{config['server']['port']}")

    except Exception as e:
        print(e)

写入代码

使用 toml.dump(data, file_object) 方法将字典转换为 TOML 格式并写入文件:

  • data:Python 字典(要写入的内容)
  • file_object:打开的文件对象(需以写入模式打开)
import toml

def write_toml_file(file_path):
    # 1. 准备要写入的数据(Python 字典格式)
    data = {
        # 基本键值对
        "title": "TOML 示例文件",
        "version": "1.0.0",
        "enabled": True,
        "timeout": 30,

        # 嵌套表(section)
        "owner": {
            "name": "Alice",
            "dob": "1990-01-01T00:00:00Z",  # 日期时间格式
            "contact": {
                "email": "alice@example.com",
                "phone": "+123456789"
            }
        },

        # 数组
        "servers": [
            {
                "name": "primary",
                "ip": "192.168.1.1",
                "ports": [80, 443]
            },
            {
                "name": "secondary",
                "ip": "192.168.1.2",
                "ports": [8080]
            }
        ],

        # 布尔值和数字
        "settings": {
            "max_connections": 100,
            "debug_mode": False,
            "threshold": 0.95
        }
    }

    try:
        # 2. 写入数据到 TOML 文件
        with open(file_path, 'w', encoding='utf-8') as f:
            toml.dump(data, f)  # 将字典转换为 TOML 格式并写入
        print(f"成功写入 TOML 文件: {file_path}")

        # 3. 验证写入结果(可选)
        with open(file_path, 'r', encoding='utf-8') as f:
            print("\n文件内容预览:")
            print(f.read())

    except Exception as e:
        print(f"写入失败: {str(e)}")

if __name__ == "__main__":
    # 写入到当前目录下的 example.toml
    write_toml_file("example.toml")

上述代码会生成如下格式的 example.toml:

title = "TOML 示例文件"
version = "1.0.0"
enabled = true
timeout = 30

[owner]
name = "Alice"
dob = "1990-01-01T00:00:00Z"

[owner.contact]
email = "alice@example.com"
phone = "+123456789"

[[servers]]
name = "primary"
ip = "192.168.1.1"
ports = [80, 443]

[[servers]]
name = "secondary"
ip = "192.168.1.2"
ports = [8080]

[settings]
max_connections = 100
debug_mode = false
threshold = 0.95

注意事项

  • 编码问题:打开文件时指定 encoding='utf-8' 避免中文等特殊字符乱码
  • 数据类型对应:
    • Python 字典 → TOML 表([section])
    • Python 列表 → TOML 数组([[array-table]] 用于列表中的字典)
    • 日期时间需用字符串表示,且符合 ISO 8601 格式
  • 格式化:toml.dump() 会自动处理缩进和格式,生成标准的 TOML 文件

通过这种方式,可以方便地将 Python 数据结构写入为 TOML 格式,适合配置文件、数据存储等场景。

关键说明

1. 数据类型自动转换

TOML 中的类型会自动映射为 Python 类型:

  • 字符串 → str
  • 整数/浮点数 → int/float
  • 布尔值 → bool
  • 数组 → list
  • 表([table])→ dict

2. 错误处理 :

  • 文件不存在:抛出 FileNotFoundError
  • 格式错误(如语法错误、类型不匹配):抛出解析错误(TOMLDecodeError)

3. 版本选择 :

  • Python 3.11+:优先使用内置 tomllib(无需额外依赖,更安全)
  • 低版本 Python:使用 toml 库(功能兼容,安装简单)

4. 写入 TOML:

  • tomllib 仅支持读取(无写入功能)
  • 若需生成 TOML 文件,可使用 toml 库的 toml.dump() 方法:
    import toml
    data = {"app": {"name": "NewApp", "version": "2.0.0"}}
    with open("new_config.toml", "w") as f:
      toml.dump(data, f)
    

原文出处:/show_1GW1licUfbux.html