当前位置: 首页 > news >正文

Python配置文件格式——INI、JSON、YAML、XML、TOML

文章目录

  • 对比
  • INI
  • JSON
  • YAML
  • XML
  • TOML
  • 参考文献

对比

格式优点缺点是否支持注释
INI简单易懂
语言内置支持
不支持复杂数据结构
JSON支持复杂数据结构阅读起来不够直观×
YAML简洁有序
支持复杂数据结构
灵活但有歧义
不同实现有兼容性问题
XML支持复杂数据结构和命名空间语法冗长体积较大
TOML语法简洁
支持复杂数据结构
相对较新




INI

键值分隔符为 =:

注释符为 #;

缺乏统一的标准,不能表示复杂数据结构,常用于 Windows 程序

config.ini

[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true[Multiline Values]
chorus: I'm a lumberjack, and I'm okayI sleep all night and I work all day[No Values]
key_without_value
empty string value here =[You can use comments]
# like this
; or this# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.[Sections Can Be Indented]can_values_be_as_well = Truedoes_that_mean_anything_special = Falsepurpose = formatting for readabilitymultiline_values = arehandled just fine aslong as they are indenteddeeper than the first lineof a value# Did I mention we can indent comments, too?
import configparserconfig = configparser.ConfigParser(allow_no_value=True)
config.read('config.ini', encoding='utf-8')for section in config.sections():print(section)for key, value in config.items(section):print('  {} = {}'.format(key, value))

特殊字符如 % 会报错 configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%xxxx'

可以用 %% 或者 config.get('MYSQL', 'PASSWORD', raw=True)




JSON

常用于 JavaScript、Python、Node.js、Ruby

config.json

{"mysql": {"host": "127.0.0.1","user": "root","password": "123456","port": 3306,"database": "mysql"}
}
import jsonconfig = json.load(open('config.json'))
print(config)




YAML

YAML 官网

注释符为 #

常用于 Python、Java、Go 等

config.yaml

language: python
mysql:host: localhostport: 3306username: userpassword: secretfields:- id- name- age

安装

pip install PyYAML
import yamlconfig = yaml.safe_load(open('config.yaml', 'r', encoding='utf-8'))
print(config)




XML

注释符为 <!-- 结合 -->

常用于 Java、C#、.NET、Scala 等

<config><database><host>localhost</host><port>3306</port><username>user</username><password>secret</password></database>
</config>
import xml.etree.ElementTree as ETtree = ET.parse('config.xml')
root = tree.getroot()
config = {}
for child in root:config[child.tag] = {subchild.tag: subchild.text for subchild in child}
print(config)




TOML

注释符为 #

常用于 Python、Rust、Go 等

config.toml

# This is a TOML documenttitle = "TOML Example"[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00[database]
enabled = true
ports = [ 8000, 8001, 8002 ]
data = [ ["delta", "phi"], [3.14] ]
temp_targets = { cpu = 79.5, case = 72.0 }[servers][servers.alpha]
ip = "10.0.0.1"
role = "frontend"[servers.beta]
ip = "10.0.0.2"
role = "backend"

Python 3.11 标准库开始有 tomllib

import tomllibconfig = tomllib.load(open('config.toml', 'rb'))
print(config)

其余版本使用 toml

pip install toml
import tomlconfig = toml.load(open('config.toml', 'r'))
print(config)




参考文献

  1. configparser — Python 文档
  2. json — Python 文档
  3. PyYAML Documentation
  4. xml.etree.ElementTree — Python 文档
  5. tomllib — Python 文档
  6. 常见配置文件格式
  7. 给力!Python配置文件,这一篇就够了!
http://www.lryc.cn/news/422953.html

相关文章:

  • The First项目报告:Web3人生模拟器,DegenReborn带你重开币圈
  • 燃气经营企业从业人员考试真题及答案
  • 白骑士的Matlab教学进阶篇 2.1 数据可视化
  • 2024年8月 | 涉及侵权、抄袭洗稿违规行为公示
  • 操作系统快速入门(四)
  • 前缀异或优化
  • AI学习指南深度学习篇-卷积神经网络中的正则化和优化
  • AutoGen Studio 本地源码构建
  • 医疗陪诊系统源码详解:在线问诊APP开发的技术要点
  • VSCode编译多个不同文件夹下的C++文件
  • 【安卓】连接真机和使用通知
  • CSS3下拉菜单实现
  • Mysql8.3.0排序导致分页数据错乱
  • 漏洞复现-Cacti命令执行漏洞 (CVE-2022-46169)
  • 【Ajax使用说明】Ajax、Axios以及跨域
  • IIS网站搬家工具WebDeploy(把网站迁移去另一台服务器)
  • SQL Server 2022的游标
  • 「11月·香港」第三届人工智能、人机交互和机器人国际学术会议(AIHCIR 2024)
  • 【redis】springboot 用redis stream实现MQ消息队列 考虑异常ack重试场景
  • 初识IDEA
  • zigbee笔记:十、ZStack(2.3.0-1.4.0)的OSAL使用分析
  • SpringBoot响应式编程(1)Reactor核心
  • Java后端处理前端字符串与 JSON 数据:安全拼接与转义技巧
  • 一文搞懂bfs,dfs和高级图算法
  • 【Rust光年纪】Rust异步编程利器:异步DNS、高性能Web服务器一网打尽
  • 04学生管理系统(栈)
  • 我们如何在centos上部署批量管理工具ansible
  • 如何评估前端代码审查培训计划的有效性?
  • 使用nvm切换Node.js版本
  • x264 编码器 PSNR算法源码分析