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

embedded/2024/10/20 5:02:35/
xmlns="http://www.w3.org/2000/svg" style="display: none;">

文章目录

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

对比

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




python.org/zh-cn/3/library/configparser.html" rel="nofollow">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?
python">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)




python.org/zh-cn/3/library/json.html" rel="nofollow">JSON

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

config.json

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




yaml.org/wiki/PyYAMLDocumentation" rel="nofollow">YAML

YAML 官网

注释符为 #

常用于 Python、Java、Go 等

config.yaml

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

安装

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




python.org/zh-cn/3/library/xml.etree.elementtree.html#module-xml.etree.ElementTree" rel="nofollow">XML

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

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

xml"><config><database><host>localhost</host><port>3306</port><username>user</username><password>secret</password></database>
</config>
python">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)




python.org/zh-cn/3/library/tomllib.html" rel="nofollow">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

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

其余版本使用 toml

pip install toml
python">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.ppmy.cn/embedded/94648.html

相关文章

四数相加2 | LeetCode-454 | 哈希集合 | Java详细注释

&#x1f64b;大家好&#xff01;我是毛毛张! &#x1f308;个人首页&#xff1a; 神马都会亿点点的毛毛张 &#x1f579;️思路&#xff1a;四数相加 > 两数相加 &#x1f4cc;LeetCode链接&#xff1a;454. 四数相加 II 文章目录 1.题目描述&#x1f34e;2.题解&#x…

2024年8月7日(mysql主从 )

回顾 主服务器 [rootmaster_mysql ~]# yum -y install rsync [rootmaster_mysql ~]# tar -xf mysql-8.0.33-linux-glibc2.12-x86_64.tar [rootmaster_mysql ~]# tar -xf mysql-8.0.33-linux-glibc2.12-x86_64.tar.xz [rootmaster_mysql ~]# cp -r mysql-8.0.33-linux-glibc2.…

手机怎么远程控制电脑屏幕?手机远程控制电脑方法分享

手机与电脑之间的互联互通变得越来越便捷。 无论是工作还是学习&#xff0c;有时我们需要在手机上远程控制电脑屏幕&#xff0c;以完成一些复杂的操作或查看电脑上的文件。 本文将详细介绍几种实用的手机远程控制电脑屏幕的方法&#xff0c;帮助读者轻松实现这一目标。 一、使…

Linux磁盘配额

系列文章目录 提示&#xff1a;仅用于个人学习&#xff0c;进行查漏补缺使用。 1.Linux介绍、目录结构、文件基本属性、Shell 2.Linux常用命令 3.Linux文件管理 4.Linux 命令安装(rpm、install) 5.Linux账号管理 6.Linux文件/目录权限管理 7.Linux磁盘管理/文件系统 8.Linu…

多因素考量,探寻场外期权合约期内的潜力股

在金融投资的广阔天地中&#xff0c;场外期权作为一种灵活且颇具潜力的工具&#xff0c;为投资者开辟了多样的策略路径。其中&#xff0c;选股策略极为关键&#xff0c;特别是关注股票在场外期权合约期限内的上涨可能性等诸多方面&#xff0c;对于挖掘潜力个股意义重大。 首先&…

leetcode787. K 站中转内最便宜的航班——优先队列优化的Dijkstra算法+剪枝

题目 leetcode787. K 站中转内最便宜的航班 题目分析 给定一个城市图&#xff0c;每个城市通过航班与其他城市相连。每个航班都有一个起点、终点和价格。你需要找到从起点城市 src 到终点城市 dst 的最便宜路径&#xff0c;但这条路径最多只能经过 k 个中转站。你需要返回这…

基于华为atlas下的yolov5+BoT-SORT/ByteTrack煤矿箕斗状态识别大探索

写在前面&#xff1a; 本项目的代码原型基于yolov5yolov8。其中检测模型使用的yolov5&#xff0c;跟踪模型使用的yolov8。 这里说明以下&#xff0c;为什么不整体都选择yolov8呢&#xff0c;v8无疑是比v5优秀的&#xff0c;但是atlas这块经过不断尝试没有过去&#xff0c;所以…

【数据结构】五、树:8.并查集

4.并查集Disjoint Set 文章目录 4.并查集Disjoint Set4.1查4.2并❗4.3代码实现4.4对union优化4.5对Find的优化&#xff08;压缩路径&#xff09;❗4.6并查集C代码&#xff08;优化后&#xff09;按秩合并 集合。在集合中将各个元素划分为若干个 互不相交的子集。 如何表示&quo…