📜  python 读取 toml 文件 - Python (1)

📅  最后修改于: 2023-12-03 15:04:18.821000             🧑  作者: Mango

Python 读取 TOML 文件

简介

TOML(Tom's Obvious, Minimal Language)是一种类似于INI格式但更加强大和易用的配置文件格式,其目标是提供一种易于阅读和编写的格式,同时具有强大的功能。

Python提供了多种库可以读取TOML格式的配置文件,其中最流行的是toml库pytoml库,两者的API接口非常相似,可以根据自己的需求选择使用。

安装

在使用之前,需要先安装相应的TOML库。可以通过pip命令进行安装:

pip install toml

或者:

pip install pytoml
基本使用

通过TOML库,读取TOML格式的配置文件非常简单:

import toml

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

或者:

import pytoml

with open('config.toml', 'r') as f:
    config = pytoml.load(f)

以上代码将读取当前目录下名为config.toml的文件,并将其转换成一个Python字典。

高级用法

TOML格式的配置文件可以包含多个section,以及复杂的数据结构(如列表、字典等)。TOML库提供了一些 API 接口来处理这些通用的用例。

读取指定的 section
config = toml.load('config.toml')
database_config = config['database']

以上代码读取了config.toml文件,并返回了其中名为"database"的section。

从字符串读取
config_str = """
[database]
host = "localhost"
port = 5432
username = "root"
password = "root"
"""

config = toml.loads(config_str)

以上代码将字符串转换成Python字典。

写入 TOML 文件
config = {
    'database': {
        'host': 'localhost',
        'port': 5432,
        'username': 'root',
        'password': 'root'
    }
}

with open('config.toml', 'w') as f:
    toml.dump(config, f)

以上代码将Python字典写入到一个TOML格式的配置文件中。

结论

在Python中读取TOML格式的配置文件非常容易,只需要安装一个TOML库即可。TOML格式的易于阅读和编写,并支持多个section和复杂的数据结构,非常适合用于配置文件。