ZetCode

Python TOML

最后修改于 2024 年 1 月 29 日

在本文中,我们展示了如何在 Python 中使用 TOML 配置文件格式。我们使用 `tomllib` 模块,该模块在 Python 3.11 中引入。

TOML 格式

YAML (Tom's Obvious Minimal Language) 是一种人类可读的数据序列化语言。它是一种易于阅读的最小配置文件格式。

TOML 支持以下类型

TOML 文件具有 `.toml` 扩展名。

Python tomllib 模块

这个 `tomllib` 提供了解析 TOML 的接口。它不支持写入 TOML 文件。

该模块定义了两个函数。`tomllib.load` 从文件解析 TOML。`tomllib.loads` 从字符串解析 TOML。

以下是 TOML 到 Python 的数据转换表。

TOMLPython
字典
字符串字符串
整数int
floatfloat
布尔值布尔值
本地日期时间datetime.datetime
本地日期datetime.date
本地时间datetime.time
数组列表

Python TOML 简单示例

下面是一个简单的 TOML 示例。

simple.py
#!/usr/bin/python

import tomllib

source = """
name = "John Doe"
occupation = "gardener"
"""

data = tomllib.loads(source)

for e in data.items():
    print(e)

print('----------------------------')

for e in data.keys():
    print(e)

print('----------------------------')

for e in data.values():
    print(e)

在程序中,我们从字符串加载 TOML 数据并打印加载的键值对、键和值。

source = """
name = "John Doe"
occupation = "gardener"
"""

在 TOML 字符串中,我们定义了两个键/值对。

data = tomllib.loads(source)

我们使用 `tomllib.loads` 从字符串加载 TOML 数据。

for e in data.items():
  print(e)

我们使用 `items` 方法迭代键值对。

for e in data.keys():
  print(e)

我们使用 `keys` 方法迭代键。

for e in data.values():
  print(e)

最后,我们使用 `values` 方法循环遍历值。

$ ./simple.py
('name', 'John Doe')
('occupation', 'gardener')
----------------------------
name
occupation
----------------------------
John Doe
gardener

Python TOML 从文件读取

我们使用 `tomllib.load` 方法从文件解析 TOML。

data.toml
# Simple TOML document

title = "Simple document"

[data]
enabled = true
words = ['sky', 'note', 'cup', 'toast', 'falcon']
vals = [2, 3, 1, 6, 5, 3, 9]

我们有一个 TOML 文件。

title = "Simple document"

这是一个 TOML 键/值对。

[data]
enabled = true
words = ['sky', 'note', 'cup', 'toast', 'falcon']
vals = [2, 3, 1, 6, 5, 3, 9]

这是一个 TOML 表。

read_file.py
#!/usr/bin/python

import tomllib

fname = 'data.toml'

with open(fname, 'rb') as f:
    
    data = tomllib.load(f)

    title = data.get('title')
    print(title)

    enabled = data.get('data')['enabled']
    print(enabled)

    words = data.get('data')['words']
    print(words)

    vals = data['data']['vals']
    print(vals)

我们从文件读取 TOML 数据。

data = tomllib.load(f)

我们加载 TOML 数据。

title = data.get('title')

我们使用 `get` 获取键的值。

enabled = data.get('data')['enabled']

从名为 `data` 的 TOML 表中,我们获取 `enabled` 的值。

words = data.get('data')['words']
print(words)

从同一个表中,我们获取 `words` 数组。

$ ./read_file.py
Simple document
True
['sky', 'note', 'cup', 'toast', 'falcon']
[2, 3, 1, 6, 5, 3, 9]

多行 TOML 数组

TOML 数组可以跨越多行。

multiple.toml
words = [
  "small",
  "cup",
  "forest",
  "toast",
  "mold"
]

我们定义了一个 `words` 数组。

multiple.py
#!/usr/bin/python

import tomllib

fname = 'multiple.toml'

with open(fname, 'rb') as f:

    data = tomllib.load(f)
    print(data['words'])
    print(data['words'][0])
    print(data['words'][1])

我们解析 TOML 文件并打印数组值。

$ ./multiple.py
['small', 'cup', 'forest', 'toast', 'mold']
small
cup

Python TOML 类型转换

在下一个示例中,我们展示了 TOML 到 Python 的类型转换。

types.toml
married = false
dob = 1999-09-20
weight = 58.5
siblings = 2
favcols = ['red', 'blue']

我们有几对不同类型的键值对。

dtypes.py
#!/usr/bin/python

import tomllib

fname = 'types.toml'

with open(fname, 'rb') as f:

    data = tomllib.load(f)
    
    print(type(data['married']))
    print(type(data['dob']))
    print(type(data['weight']))
    print(type(data['siblings']))
    print(type(data['favcols']))

我们解析键值对并打印每个值的 Python 数据类型。我们使用内置的 `type` 函数。

$ ./dtypes.py
<class 'bool'>
<class 'datetime.date'>
<class 'float'>
<class 'int'>
<class 'list'>

Python TOML 解码错误

如果 TOML 文档无效,则会引发 `TOMLDecodeError`。

decode_error.py
#!/usr/bin/python

import tomllib

source = """
name = "John Doe"
occupation: "gardener"
"""

try:
    data = tomllib.loads(source)
    name = data['name']
    occupation = data['occupation']

    print(name)
    print(occupation)

except tomllib.TOMLDecodeError as e:
    print('Invalid TOML document')
    print(e)

在此示例中,我们在字符串中解析一个无效的 TOML 文档。

$ ./decode_error.py
Invalid TOML document
Expected '=' after a key in a key/value pair (at line 3, column 11)

来源

Python tomllib — 解析 TOML 文件

在本文中,我们在 Python 中使用了 TOML 格式。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程