解决Python写入yaml后排版混乱还丢失注释问题

2023-04-07编程技术16636

转载https://www.cnblogs.com/jiahm/category/1530828.html

大家有没有遇到过在使用Python进行yaml文件写入数据后,内容排版混乱并且丢失注释问题,非常不友好,如下图所示:

针对上述问题,简单的解决方法如下:

安装pip install ruamel.yaml

使用:

ruamel.yaml.load(Loader=ruamel.yaml.RoundTripLoader) 
ruamel.yaml.dump(Dumper=ruamel.yaml.RoundTripDumper) 

ruamel.yaml.round_trip_load() 
ruamel.yaml.round_trip_dump() 
示例代码如下:

from ruamel import yaml
def setDictYaml(self, fileDir, fileName, key, value):
with open(filePath(fileDir, fileName), 'r', encoding="utf-8") as f:
doc = yaml.round_trip_load(f)
doc[key] = value
with open(filePath(fileDir, fileName), 'w', encoding="utf-8") as f:
yaml.round_trip_dump(doc, f, default_flow_style=False)
setDictYaml(fileDir='config', fileName='config.yaml', key='password', value=123)

运行后的结果如上图所示,问题完美解决!

解决Python写入yaml后排版混乱还丢失注释问题的相关教程结束。

本文地址:https://www.ufcn.cn/tutorials/2423704.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!