TOML 文件 & Python 完整教程

TOML 文件 & Python 完整教程 · TOML Guide

TOML 文件 & Python 零基础完整教程

什么是TOML、语法规则、tomllib/tomli库、读写配置、pyproject.toml实战、对比JSON/YAML

一、什么是 TOML

TOML 全称 Tom’s Obvious, Minimal Language,是一种专为配置文件设计的标准化、强类型文本格式,标准后缀 .toml

核心定位:专门给程序项目用配置,Python 官方标准项目配置文件 pyproject.toml 就是 TOML。

TOML 四大核心特点

层级清晰 使用 [表名] 分段,层级一目了然

强类型 原生支持数字、布尔、日期、数组,无类型歧义

无多余符号 不需要逗号、大括号,比JSON简洁

Python 官方标准 PEP 621 规定项目元数据统一使用 pyproject.toml

二、TOML 主流使用场景

  • Python 项目标准配置:pyproject.toml(依赖、构建工具、Ruff/Pytest配置)
  • Rust 项目 Cargo.toml(标配)
  • uv、poetry、pipenv、pdm 包管理器配置
  • Ruff、Black、isort、mypy 代码工具配置
  • 后端程序应用配置、服务参数文件

三、TOML vs JSON vs YAML 对比

格式设计目标类型支持分段能力Python原生支持典型用途
JSON 数据传输 基础类型有限,无日期 多层大括号嵌套,难阅读 内置json库 接口请求响应
YAML 通用配置 丰富,但缩进敏感易出错 缩进分层,Tab报错 需安装pyyaml K8s、CI脚本
TOML 项目配置专用 原生日期、整数、浮点数、布尔 [table] 分段,完全不怕缩进 3.11+内置tomllib Python/Rust项目配置

TOML 示例(清晰分段)

[server]
host = "127.0.0.1"
port = 8000
debug = true

[database]
user = "root"

同等JSON(嵌套繁琐)

{
  "server": {
    "host": "127.0.0.1",
    "port": 8000,
    "debug": true
  },
  "database": {
    "user": "root"
  }
}

四、TOML 完整基础语法

基础规则:键值对用 = 分隔;字符串双引号;注释 #;分段用 [table]

4.1 基础键值对(全局无分段)

name = "PythonDemo"
version = 0.1.0
is_release = false
count = 100
create_time = 2026-07-08T10:30:00
empty_val = null

4.2 表 [table] 分段(最核心特性)

[表名] 代表一组独立配置,下面所有键值都属于这个表

[app]
name = "测试项目"
debug = true

[db.mysql]  # 嵌套表 db下的mysql
host = "127.0.0.1"
port = 3306

4.3 数组/列表


4.4 内联表(单行嵌套对象)

info = { id = 1, username = "admin" }

4.5 注释

# 整行注释
port = 8000  # 行尾注释也支持

五、Python 解析 TOML 的库

Python3.11+ 内置 tomllib(推荐)

# 无需安装,标准库 import tomllib
只读,仅支持加载文件,不支持写入

tomli(3.10及以下兼容)

API和tomllib完全一致,低版本兼容

tomli-w 写入库

唯一稳定写入TOML的官方工具
组合方案:读取 tomllib / tomli;写入 tomli-w

六、Python 读取 TOML 文件

6.1 准备 config.toml

[app]
name = "后端服务"
debug = true

[db]
host = "127.0.0.1"
port = 3306
pool_size = 10

6.2 Python3.11+ 读取代码(tomllib)

import tomllib

# 二进制模式 rb 打开(tomllib强制二进制读取)
with open("config.toml", "rb") as f:
    cfg = tomllib.load(f)

# 读取全局、分段数据
print(cfg["app"]["name"])
print(cfg["db"]["host"])
print(cfg["db"]["port"])

6.3 低版本 Python(<=3.10)兼容写法

try:
    import tomllib
except ModuleNotFoundError:
    import tomli as tomllib

with open("config.toml", "rb") as f:
    cfg = tomllib.load(f)

七、Python 写入/修改 TOML 文件

内置tomllib只支持读取,写入需要 tomli-w

7.1 安装写入库

pip install tomli-w

7.2 全新写入 TOML

import tomli_w

data = {
    "app": {"name": "新服务", "debug": False},
    "db": {"host": "127.0.0.1", "port": 3306}
}

# wb 二进制写入
with open("new_config.toml", "wb") as f:
    tomli_w.dump(data, f)

7.3 修改已有 TOML 文件

import tomllib
import tomli_w

# 1.读取
with open("config.toml", "rb") as f:
    cfg = tomllib.load(f)

# 2.修改字段
cfg["app"]["debug"] = False
cfg["db"]["port"] = 3307

# 3.写回原文件
with open("config.toml", "wb") as f:
    tomli_w.dump(cfg, f)

八、核心实战:pyproject.toml 详解

pyproject.toml 是现代Python项目标准配置文件,所有工具统一放这里,替代多个ini/cfg。

[build-system]
# 项目构建依赖
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
# 项目基础元数据
name = "python-demo"
version = "0.1.0"
authors = [{ name = "张三", email = "zhangsan@xxx.com" }]
dependencies = [
    "fastapi>=0.100",
    "sqlalchemy>=2.0"
]

[tool.ruff]
# Ruff代码检查配置
line-length = 88
select = ["E", "W", "F", "I"]

[tool.pytest.ini_options]
# pytest测试配置
testpaths = ["tests"]

常用分段说明

[build-system] 打包构建工具

[project] 项目名称、版本、依赖(PEP621标准)

[tool.xxx] 各类第三方工具配置(ruff/pytest/mypy)

九、常见报错与排坑

TOMLParseError 语法解析失败 中文写入变成转义字符
报错现象根因解决方案
tomllib.load() 报编码错误 使用 r 文本模式打开 必须 open(path, "rb") 二进制
ModuleNotFoundError: tomllib Python版本<3.11 安装tomli,import tomli as tomllib
tomllib无dump方法 内置库只可读不可写 安装tomli-w做写入
字符串单引号、数组逗号多余 统一双引号,数组末尾不加逗号
tomli-w默认转义 dump(data, f, multiline_strings=True)

十、速记总结

TOML + Python 核心口诀

1. 后缀.toml,[table]分段,专为项目配置而生

2. Py3.11+内置tomllib,只读、rb二进制打开

3. 写入必须安装tomli-w,wb模式导出

4. 现代Python项目标配pyproject.toml统一管理依赖与工具

5. 对比YAML:无缩进坑;对比JSON:分层清晰更易维护

使用建议:新项目统一使用 pyproject.toml 管理所有配置,不再分散多个ini、yaml文件。

TOML File & Python Complete Guide

What is TOML, syntax, tomllib/tomli, read/write, pyproject.toml, compare JSON/YAML

1. What is TOML

TOML = Tom's Obvious, Minimal Language, config file format with extension .toml.

Core Standard: PEP 621 defines pyproject.toml as official Python project config file.

TOML Features

[table] clear sections

Native date, int, float, bool support

No messy braces/nested brackets like JSON

Official Python standard

2. Common Use Cases

  • Python: pyproject.toml (dependencies, ruff, pytest)
  • Rust: Cargo.toml
  • uv / poetry / pdm package managers
  • Linter & formatter config (Ruff, Black)

3. TOML vs JSON vs YAML

JSON: data transmission, heavy nested braces.

YAML: indent-sensitive, easy syntax error.

TOML: dedicated for project config, section-based via [table], no indent bugs.

4. Basic TOML Syntax

# key-value
name = "demo"
port = 8000

# table section
[server]
host = "127.0.0.1"

# nested table
[db.mysql]

# array
tags = ["python", "toml"]

5. Python Libraries

  • Python 3.11+: built-in tomllib (read only, open with rb)
  • Python <3.11: install tomli, same API
  • Write TOML: install tomli-w

6. Read TOML Example

import tomllib

with open("config.toml", "rb") as f:
    data = tomllib.load(f)

print(data["server"]["port"])

7. Write TOML Example

import tomli_w

data = {"server": {"port": 8000}}
with open("out.toml", "wb") as f:
    tomli_w.dump(data, f)

8. pyproject.toml Demo

[project]
name = "demo"
version = "0.1.0"
dependencies = ["fastapi"]

[tool.ruff]
line-length = 88

9. Common Errors

  • tomllib requires "rb" binary mode
  • No dump() in tomllib; use tomli-w
  • Old Python needs tomli package

10. Quick Cheat Sheet

.toml = section-based config file

Read: tomllib / tomli (rb mode)

Write: tomli-w (wb mode)

Modern Python project uses pyproject.toml as single config entry