
- YAML全称
YAML Aint't a Markup Language(YAML不是一种标记语言),是一种易读的序列化语言 - 通常应用在一些数据代码分离的场合,比如
配置文件中
python的PyYaml模块是Python的YAML解析器和生成器
def read_yaml():
with open(path, "r", encoding="utf-8") as f:
result = f.read()
result = yaml.load(result, Loader=yaml.FullLoader)
print(result)
# 也可以写成如下代码
def read_yaml():
with open(path, "r", encoding="utf-8") as f:
result = f.read()
result = yaml.full_load(result)
print(result)
针对不同的需要,加载器有如下的集中类型:
BaseLoader仅加载最基本的YAMLSafeLoader安全地加载YAML语言的子集。建议用于加载不受信任的输入(safe_load)
FullLoader加载完整YAML语言。避免任意代码执行。
这是默认加载器(full_load)
UnsafeLoader也称为Loader向后兼容性,原始的Loader代码,不受信任的数据可能通过这种方式执行其他有危害的代码
def write_yaml():
with open(path, "w", encoding="utf-8") as f:
yaml.dump(data, f, Dumper=yaml.SafeDumper)
3、YAML支持的数据类型
对象键值对的集合,又称为映射(mapping)/哈希(hashes)/字典(dictionary)数组一组按次序排列的值,又称为序列(sequence)/列表(list)纯量(scalars)单个的、不可再分的值
- 大小写敏感
- 使用缩进表示层级关系,缩进的空格数不重要,相同层级的元素左侧对其即可
- 缩进时不可以使用Tab,只允许空格(Pycharm在yaml文件会默认使用两个空格替换Tab)
#表示注释- 字典的键值对通过
:表示,列表的项通过-表示
-
情况一:值为字符串
animals: dogs -
表示为python的字典为:
{ "animal": "dogs" } -
情况二:值为字典
person: { name: Steve, age: 18 }{ "person": { "name": "Steve", "age": 18 } } -
情况三:值为列表
lists: [ 1,2,3 ]{ "lists": [ 1, 2, 3 ] } -
情况四:没有元组这种类型
tuples: (1,2,3){ "tuplers": "(1,2,3)" }
- 一种复杂的情况:
cool_list: - 10 - 12 - 15 hard_list: - { key: value } - [ 1,2,3 ] - test: - 1 - 2 - 3 twice_list: - - { a: b } - { c: d } - { e: f }{ "cool_list": [ 10, 12, 15 ], "hard_list": [ { "key": "value" }, [ 1, 2, 3 ], { "test": [ 1, 2, 3 ] } ], "twice_list": [ [ { "a": "b" }, { "c": "d" }, { "e": "f" } ] ] }
纯量是最基本的、不可再分的值,以下是一些常见的类型
int: 12
float: 12.3
string: hello
bool_1: true
None: null
time: 2022-04-10t22:39:32.10-05:00
date: 2022-04-10
表示为
{
'int': 12,
'float': 12.3,
'string': 'hello',
'bool': True,
'None': None,
'time': datetime.datetime(2022, 4, 10, 22, 39, 32, 100000, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400)))
'date': datetime.date(2022, 4, 10)
}
- 说明:
- 时间和日期需要使用
ISO 8601格式,日期格式需为yyyy-MM-dd - bool类型:true、True、false、False都可以,如果要表示为字符串,加上引号即可
"true" - 可以使用
~表示null
- 时间和日期需要使用
- 字符串默认不使用引号
''""包裹 - 但是当有
空格或者特殊字符时,则最好使用引号 - 双引号不会对特殊字符转义
str1: "\n22" str2: '\n33'{'str1': '\n22', 'str2': '\n33'}
- YAML使用两个感叹号强制转换数据类型
转换后表示为:intToStr: !!str 123 boolToStr: !!str true strToFloat: !!float '12.22'{ "intToStr": "123", "boolToStr": "true", "strToFloat": 12.22 }
参考文章:
https://www.cnblogs.com/poloyy/p/12482510.html
https://www.cnblogs.com/poloyy/p/12448509.html
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)