yaml文件读写操作

1、读取yaml:load()

data.yaml文件:

#字典
name: "hello"

读取data.yaml文件:

import yaml
 
def main():
    with open("./data.yaml","r") as f:
    data=yaml.load(f,Loader=yaml.FullLoader)
    print(data)
 
if __name__ == '__main__':
    main()

注意:要加上Loader=yaml.FullLoader,否则会报错:YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.

运行结果:

 

 

2、写入yaml文件:dump()

data={"S_data":{"test1":"hello"},"Sdata2":{"name":"汉字"}}

写入操作:

#coding=gbk
import yaml
 
def main():
    #写入数据:
    data={"S_data":{"test1":"hello"},"Sdata2":{"name":"汉字"}}
    with open("./data.yaml","w") as f:
        yaml.dump(data,f,encoding='utf-8',allow_unicode=True)
if __name__ == '__main__':
    main()

注意:data数据中有汉字时,加上:encoding='utf-8',allow_unicode=True

运行结果:

 

posted @ 2021-01-23 10:30  似梦千寻  阅读(1121)  评论(0)    收藏  举报