截至我的知识库信息(2025年5月),Python 3.11及以上版本内置了 tomllib 模块用于解析TOML文件。

具体情况如下:
-
Python 3.11+:标准库中新增了
tomllib模块,你可以直接使用import tomllib来解析TOML格式的字符串或文件。import tomllib # 从文件读取 with open("config.toml", "rb") as f: data = tomllib.load(f) # 从字符串解析 toml_str = """= "示例TOML" [owner] name = "Tom" """ data = tomllib.loads(toml_str) -
Python 3.10 及更早版本:没有内置的TOML解析器,你需要使用第三方库,
toml或tomli(注意,tomli是Python 3.11中tomllib的前身)。
- 如果你使用 Python 3.11+,直接使用
import tomllib即可(无需安装任何东西)。 - 如果你使用 Python 3.10 或更早版本,需要安装第三方库(推荐
pip install tomli,因为tomllib的API与tomli兼容,便于未来迁移)。
注意: 标准库的 tomllib 目前只支持读取(解析),不支持将Python对象写入TOML文件,如果需要将数据保存为TOML格式,仍然需要使用第三方库(如 tomli_w 或 toml)。