python对yaml文件进行操作

python对yaml文件进行操作


读取yaml文件

yaml文件转字典

import yaml
# 读取yaml文件
with open(r'data.yaml','r',encoding='utf-8') as f:
    yaml_file = yaml.safe_load(f)
# yaml文件会转化为字典
print(yaml_file)
# 获取字典中的值
print(yaml_file['path'])

写yaml文件

字典转yaml文件

test_data_dict = {
    'path': '1',
    'train': '2',
    'val': '3',
    'names': [1,2,3],
    'sub1':{
        'test1': '9',
        'test2': '8',
        'test3': '7',
    }
}

with open(r'test.yaml',mode='w',encoding='utf-8') as f:
    yaml.dump(test_data_dict,stream=f)

你可能感兴趣的:(yaml)