python 如何修改yaml文件?
需求 :yaml文件可以作为python工程的参数配置,那么,当我们需要修改yaml文件该怎么办呢?
安装ruamel.yaml第三方库
(查资料显示,用pyyaml库的时候,读取再写回,会导致格式错乱,故这里选用了ruamel.yaml第三方库)
pip install ruamel.yaml
1.原始yaml文件为
2.执行修改代码
from ruamel.yaml import YAML yaml = YAML() # *=======读取=========* with open("01.yaml", "r", encoding='utf-8') as f: data = yaml.load(f) # *=======修改内容=========* data["host_dict"]["host"] = "192.168.0.1" data["host_dict"]["port"] = 55 data["host_dict"]["username"] = "xiaoming" data["host_dict"]["pwd"] = 123456 # *=======写入=========* with open("01.yaml", "w", encoding="utf-8") as f: yaml.dump(data, f)
3.执行结束后
参考资料
https://blog.51cto.com/u_15127535/3499300
http://47.93.218.165/blog/blog/12/