...

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官方文档翻译

作者:韩志超

出处:https://www.cnblogs.com/superhin/p/python-toml.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

如有问题,请微信联系 superz-han,并发送原文链接。

posted @   韩志超  阅读(2663)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-07-06 Pytest使用pytest.ini实现环境变量控制
2020-07-06 macOS搭建Selenium Grid
2020-07-06 macOS使用Selenium测试Opera浏览器
2020-07-06 macOS使用Selenium测试新版Edge浏览器
2020-07-06 macOS使用Selenium操作Firefox浏览器
2020-07-06 macOS使用Selenium操作Safari浏览器
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu