python yaml
个人学习总结,持续更新中…….
斜体代表个人的观点或想法。
基本语法
- 大小写敏感
- 使用缩进表示层级关系
- 缩进不允许使用tab,只允许空格
- 缩进的空格数不重要,只要相同层级的元素左对齐即可
- '#'表示注释
数据类型
YAML 支持以下几种数据类型:
- 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
- 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
- 纯量(scalars):单个的、不可再分的值
示例1 读取 .yml
gt.yml
0:
- cam_R_m2c: [0.6, 0.7, 0.2]
obj_id: 19
- cam_R_m2c: [1.6, 0.7, 0.2]
obj_id: 20
- cam_R_m2c: [3.6, 0.7, 0.2]
obj_id: 17
- cam_R_m2c: [4.6, 0.7, 0.2]
obj_id: 18
test.py
import yaml
gt = 'gt.yml'
with open(gt) as f:
opt_dict = yaml.load(f, Loader=yaml.FullLoader)
print(opt_dict)
# {0: [{'cam_R_m2c': [0.6, 0.7, 0.2], 'obj_id': 19}, {'cam_R_m2c': [1.6, 0.7, 0.2], 'obj_id': 20}], 1: [{'cam_R_m2c': [3.6, 0.7, 0.2], 'obj_id': 17}, {'cam_R_m2c': [4.6, 0.7, 0.2], 'obj_id': 18}]}
print(type(opt_dict))
# <class 'dict'>
print(len(opt_dict))
# 2
示例2 读取 .yml
gt.yml
path: ../datasets/coco128 # dataset root dir
train: data/train.txt # train images (relative to 'path') 128 images
val: data/val.txt # val images (relative to 'path') 128 images
test: # test images (optional)
# Classes
nc: 10 # number of classes
names: ['combustion_lining', 'fan', 'mixer']
test.py
import yaml
gt = 'gt.yml'
with open(gt) as f:
opt_dict = yaml.load(f, Loader=yaml.FullLoader)
print(opt_dict)
# {'path': '../datasets/coco128', 'train': 'data/train.txt', 'val': 'data/val.txt', 'test': None, 'nc': 10, 'names': ['combustion_lining', 'fan', 'mixer']}
print(type(opt_dict))
# <class 'dict'>
print(len(opt_dict))
# 6
示例3 写入 .yml
test.py
import yaml
hyp1 = {'Name': 'Zara', 'Age': 7, 'score': [1, 2, 3]}
hyp2 = {0: [{'cam_R_m2c': [0.6, 0.7, 0.2], 'obj_id': 19}, {'cam_R_m2c': [1.6, 0.7, 0.2], 'obj_id': 20}],
1: [{'cam_R_m2c': [3.6, 0.7, 0.2], 'obj_id': 17}, {'cam_R_m2c': [4.6, 0.7, 0.2], 'obj_id': 18}]}
gt = 'gt.yml'
with open(gt, 'w') as f:
yaml.dump(hyp1, f, sort_keys=False)
with open(gt, 'a') as f:
yaml.dump(hyp2, f, sort_keys=False)
gt.yml
Name: Zara
Age: 7
score:
- cam_R_m2c:
- 0.6
- 0.7
- 0.2
obj_id: 19
- cam_R_m2c:
- 1.6
- 0.7
- 0.2
obj_id: 20
- cam_R_m2c:
- 3.6
- 0.7
- 0.2
obj_id: 17
- cam_R_m2c:
- 4.6
- 0.7
- 0.2
obj_id: 18
关于numpy数据
yaml不能直接写入numpy数组,虽然写入不出错,但读取会出错。
import yaml
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
hyp1 = {'a': a, 'b': b}
gt = 'gt_np.yml'
# 写入, 不出错
with open(gt, 'w') as f:
yaml.dump(hyp1, f, sort_keys=False)
# 读取, 出错
with open(gt) as f:
opt_dict = yaml.load(f, Loader=yaml.FullLoader)
print(opt_dict)
# yaml.constructor.ConstructorError: could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:numpy.core.multiarray._reconstruct'
需要通过 int() 转换一下。
import yaml
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
a1 = [int(x) for x in a]
b1 = [int(x) for x in b]
hyp1 = {'a': a1, 'b': b1}
gt = 'gt_np.yml'
# 写入, 不出错
with open(gt, 'w') as f:
yaml.dump(hyp1, f, sort_keys=False)