python 模块 tomllib 读取 TOML 配置文件

创建日期: 2025-05-08 17:28 | 作者: 风波 | 浏览次数: 6 | 分类: Python

官方文档:https://docs.python.org/3/library/tomllib.html

This module provides an interface for parsing TOML 1.0.0 (Tom’s Obvious Minimal Language, https://toml.io). This module does not support writing TOML.

This module defines the following functions:

这个模块只定义了两个函数

tomllib.load(fp, /, *, parse_float=float)

Read a TOML file. The first argument should be a readable and binary file object. Return a dict. Convert TOML types to Python using this conversion table.

parse_float will be called with the string of every TOML float to be decoded. By default, this is equivalent to float(num_str). This can be used to use another datatype or parser for TOML floats (e.g. decimal.Decimal). The callable must not return a dict or a list, else a ValueError is raised.

A TOMLDecodeError will be raised on an invalid TOML document.

tomllib.loads(s, /, *, parse_float=float)

Load TOML from a str object. Return a dict. Convert TOML types to Python using this conversion table. The parse_float argument has the same meaning as in load().

A TOMLDecodeError will be raised on an invalid TOML document.

The following exceptions are available:

exception tomllib.TOMLDecodeError Subclass of ValueError.

Examples

import tomllib

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

toml_str = """
python-version = "3.11.0"
python-implementation = "CPython"
"""

data = tomllib.loads(toml_str)

Conversion Table

类型转换

TOML Python
TOML document dict
string str
integer int
float float (configurable with parse_float)
boolean bool
offset date-time datetime.datetime (tzinfo attribute set to an instance of datetime.timezone)
local date-time datetime.datetime (tzinfo attribute set to None)
local date datetime.date
local time datetime.time
array list
table dict
inline table dict
array of tables list of dicts
6 浏览
10 爬虫
0 评论