...

Python3读写TOML文件

TOML(Tom's Obvious, Minimal Language)是一种易于阅读和编写的配置文件格式。它的设计目标是提供一种简单而灵活的方式来表示配置数据,以便于人类阅读和编辑。

基础示例

# config.toml

[server]
host = "localhost"
port = 8080

[database]
name = "mydb"
user = "myuser"
password = "mypassword"

在上面的代码中,我们定义了一个TOML格式的配置文件,包含了服务器和数据库的配置信息。通过使用[section]语法,我们可以将配置信息分组,并使用key = value语法来定义具体的配置项。

读取TOML格式的配置文件方法如下:

安装方法

pip install toml

使用方法

import toml

config = toml.load('config.toml')

print(config['server']['host'])
print(config['database']['name'])

在上面的代码中,我们首先导入了toml库。然后,我们使用toml.load()方法读取TOML格式的配置文件,并将解析结果存储在config字典中。

最后,我们可以根据需要访问config字典中的具体配置项。

多种格式及嵌套

# testcase1.toml
[testcase]
name = '测试用例1'
priority = 1  # 支持数字类型
ready = true  # 支持bool类型
tags = ['demo', 'api-test']  # 列表格式

[[testcase.steps]]  # 用例步骤列表(嵌套格式)
target = "http.get"
args = { method = "GET", url = "http://localhost:3000/api/get" }  # 支持字典格式

[[testcase.steps]]  # 用例步骤列表
target = "http.post"
args = { method = "POST", url = "http://localhost:3000/api/post", json = { a = 1, b = 2 } }

使用python读取文件内容

from pprint import pprint
import toml
data = toml.load('testcase1.toml')
pprint(data['testcase'])

运行后效果如下:

{'name': '测试用例1',
 'priority': 1,
 'ready': True,
 'steps': [{'args': {'method': 'GET', 'url': 'http://localhost:3000/api/get'},
            'target': 'http.get'},
           {'args': {'json': {'a': 1, 'b': 2},
                     'method': 'POST',
                     'url': 'http://localhost:3000/api/post'},
            'target': 'http.post'}]}

TOML和INI文件格式的区别

  • toml中变量值支持多种格式,ini中默认为字符串格式。
  • toml中字符串必须加引号,单引号,双引号都可以,ini中字符串不加引号.
  • toml中只能使用key=value形式,ini中可以使用key=valuekey : value形式.
  • toml中只支持#号注释,可以写到变量值后,也可以独占一行,ini文件中支持;#注释,一般要独占一行。
  • toml中支持字段嵌套,ini不支持。
  • toml中的选项(变量名)大小写敏感,如host,ini中选项(变量名),大小写不敏感

TOML格式的配置文件具有易读性和易编写性,同时也支持注释和多行字符串等高级特性。你可以参考TOML官方文档,了解更多详细信息和用法示例。

参考: TOML官方文档翻译

posted @ 2023-07-06 17:43  韩志超  阅读(1043)  评论(0编辑  收藏  举报