大家有没有遇到过在使用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)
运行后的结果如上图所示,问题完美解决!