python use Pyyaml and keep format

后端 未结 3 1633
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 12:56

Here is a config file, I use PyYAML to change some value from it and then I write some config, but it will change my format, it confuses me.

 $ results.yaml          


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-18 13:33

    ruamel implements a round-trip loader and dumper, try:

    import ruamel.yaml
    conf = open("results.conf", "r")
    results = ruamel.yaml.load(conf, ruamel.yaml.RoundTripLoader)
    conf.close()
    results['nas']['mount_dirs'][0] = "haha"
    with open('/home/zonion/speedio/speedio.conf', 'w') as conf:
      ruamel.yaml.dump(results, conf, ruamel.yaml.RoundTripDumper)
    

提交回复
热议问题