在现代软件开发中,配置文件扮演着至关重要的角色。而 TOML(Tom's Obvious, Minimal Language)作为一种简洁、易读的配置格式,正被越来越多的项目采用(例如 Rust 的 Cargo.toml、Python 的 pyproject.toml 等)。本文将带你从零开始,详细讲解如何在 Python 中使用 toml 模块来读取、解析和生成 TOML 配置文件。

TOML 是一种语义明确、易于阅读的配置语言,其设计目标是成为“显而易见”的配置格式。它支持键值对、数组、表(table)、内联表等结构,语法接近 INI,但功能更强大。
一个简单的 TOML 示例:
# config.tomlname = "MyApp"version = "1.0.0"debug = true[database]host = "localhost"port = 5432username = "admin"[servers] [servers.alpha] ip = "10.0.0.1" port = 8080 [servers.beta] ip = "10.0.0.2" port = 8081Python 标准库目前(截至 Python 3.11)尚未内置 TOML 支持,因此我们需要通过 pip 安装第三方库 toml:
pip install toml注意:自 Python 3.11 起,标准库新增了tomllib模块(仅用于读取),但为了兼容性和完整功能(包括写入),我们仍推荐使用第三方toml库。
使用 toml.load() 可以从文件对象中读取 TOML 内容,而 toml.loads() 则用于解析字符串。
假设我们有一个名为 config.toml 的文件(内容如上所示),我们可以这样读取它:
import toml# 从文件读取with open('config.toml', 'r', encoding='utf-8') as f: config = toml.load(f)print(config['name']) # 输出: MyAppprint(config['database']['host']) # 输出: localhostprint(config['servers']['alpha']['ip']) # 输出: 10.0.0.1你也可以直接解析字符串:
toml_string = '''name = "TestApp"debug = false'''config = toml.loads(toml_string)print(config) # {'name': 'TestApp', 'debug': False}使用 toml.dump() 可将 Python 字典写入文件,toml.dumps() 则返回格式化的 TOML 字符串。
import toml# 构建配置字典new_config = { "app": { "name": "MyAwesomeApp", "version": "2.0.0" }, "features": ["login", "chat", "notifications"]}# 写入文件with open('new_config.toml', 'w', encoding='utf-8') as f: toml.dump(new_config, f)# 或者获取字符串toml_str = toml.dumps(new_config)print(toml_str)输出的 new_config.toml 内容如下:
[app]name = "MyAwesomeApp"version = "2.0.0"features = ["login", "chat", "notifications"]TOML 与 Python 数据类型之间有清晰的对应关系:
strint / floatbooldatetime.datetimelistdict如果 TOML 文件格式不正确,toml.load() 会抛出 toml.TomlDecodeError 异常。建议使用 try-except 进行捕获:
import tomltry: with open('invalid.toml', 'r') as f: config = toml.load(f)except toml.TomlDecodeError as e: print(f"TOML 解析失败: {e}")通过本文,你已经掌握了如何在 Python 中使用 toml 模块进行配置文件的读写操作。无论是管理应用设置、存储用户偏好,还是解析项目元数据(如 pyproject.toml),TOML 都是一个优雅且高效的选择。
记住几个关键函数:
toml.load(file):从文件读取toml.loads(string):从字符串解析toml.dump(data, file):写入文件toml.dumps(data):生成字符串希望这篇 Python toml模块 教程能帮助你轻松上手 TOML 配置管理!如果你正在开发需要灵活配置的 Python 项目,不妨试试 TOML 吧!
相关 SEO 关键词:Python toml模块、TOML配置文件解析、Python读取TOML、toml库使用教程。
本文由主机测评网于2025-12-06发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025123856.html