当前位置: 首页 > 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配置文件,这一篇就够了!

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • golang使用channel实现读写锁
  • Qt使用lupdate工具生成.ts文件
  • DevOps环境搭建
  • Python | Leetcode Python题解之第326题3的幂
  • STM32 标准库移值RTThread
  • LeetCode226 翻转二叉树
  • 学习方法[1]:如何摆脱无知?(致尚未放弃学习的人)
  • Allegro如何更改过孔的网络
  • NoSQL 详细讲解
  • MySQL预处理语句(PREPARE)和动态SQL
  • linux 查看端口占用并处理
  • 【C++】特殊类的设计与类型转换
  • 「栈」实现LIFO栈(先进后出栈|堆栈|stack)的功能 / 手撕数据结构(C++)
  • DALL-E 2:当AI遇上画笔,艺术界的“魔术师”横空出世!
  • 电脑屏幕录制工具分享5款,附上详细电脑录屏教程(2024全新)
  • Angular2开发踩坑系列-生产环境编译
  • codis proxy处理流程
  • ComponentOne 2017 V2版本正式发布
  • ECMAScript6(0):ES6简明参考手册
  • exports和module.exports
  • Java超时控制的实现
  • JS专题之继承
  • leetcode讲解--894. All Possible Full Binary Trees
  • MySQL QA
  • python3 使用 asyncio 代替线程
  • Sequelize 中文文档 v4 - Getting started - 入门
  • Shadow DOM 内部构造及如何构建独立组件
  • SQL 难点解决:记录的引用
  • 阿里云前端周刊 - 第 26 期
  • 从重复到重用
  • 等保2.0 | 几维安全发布等保检测、等保加固专版 加速企业等保合规
  • 搞机器学习要哪些技能
  • 基于Mobx的多页面小程序的全局共享状态管理实践
  • 七牛云假注销小指南
  • 使用前端开发工具包WijmoJS - 创建自定义DropDownTree控件(包含源代码)
  • 为什么要用IPython/Jupyter?
  • 继 XDL 之后,阿里妈妈开源大规模分布式图表征学习框架 Euler ...
  • 整理一些计算机基础知识!
  • ​zookeeper集群配置与启动
  • ​七周四次课(5月9日)iptables filter表案例、iptables nat表应用
  • # Java NIO(一)FileChannel
  • # Swust 12th acm 邀请赛# [ K ] 三角形判定 [题解]
  • # wps必须要登录激活才能使用吗?
  • #define与typedef区别
  • #我与Java虚拟机的故事#连载13:有这本书就够了
  • (04)odoo视图操作
  • (C++)八皇后问题
  • (ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)讲解
  • (八)Docker网络跨主机通讯vxlan和vlan
  • (附源码)springboot工单管理系统 毕业设计 964158
  • (附源码)springboot掌上博客系统 毕业设计063131
  • (附源码)计算机毕业设计SSM智能化管理的仓库管理
  • (三)docker:Dockerfile构建容器运行jar包
  • (三十五)大数据实战——Superset可视化平台搭建
  • (转)Linux整合apache和tomcat构建Web服务器