tomllib — Parse TOML files - Python 3.12.0a3 documentation 编辑
New in version 3.11.
Source code: Lib/tomllib
This module provides an interface for parsing TOML (Tom’s Obvious Minimal Language, https://toml.io). This module does not support writing TOML.
See also
The Tomli-W package is a TOML writer that can be used in conjunction with this module, providing a write API familiar to users of the standard library marshal
and pickle
modules.
See also
The TOML Kit package is a style-preserving TOML library with both read and write capability. It is a recommended replacement for this module for editing already existing TOML files.
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 adict
or alist
, else aValueError
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 adict
. Convert TOML types to Python using this conversion table. The parse_float argument has the same meaning as inload()
.A
TOMLDecodeError
will be raised on an invalid TOML document.
The following exceptions are available:
- exception tomllib.TOMLDecodeError
Subclass of
ValueError
.
Examples
Parsing a TOML file:
import tomllib with open("pyproject.toml", "rb") as f: data = tomllib.load(f)
Parsing a TOML string:
import tomllib toml_str = """ python-version = "3.11.0" python-implementation = "CPython" """ data = tomllib.loads(toml_str)
Conversion Table
TOML | Python |
---|---|
table | dict |
string | str |
integer | int |
float | float (configurable with parse_float) |
boolean | bool |
offset date-time | datetime.datetime ( |
local date-time | datetime.datetime ( |
local date | datetime.date |
local time | datetime.time |
array | list |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论