【问题标题】:Problem with arrays in YAML files when serializing and deserializing [duplicate]序列化和反序列化时 YAML 文件中的数组出现问题 [重复]
【发布时间】:2021-08-30 05:37:25
【问题描述】:

我有这个简单的程序

import yaml
import sys

def main(argv):
    #dddd
    with open('file_base.yaml') as f:
        data = yaml.load(f, Loader=yaml.FullLoader)
        #print(data)
        #print(type(data))

        #Do some transformations to data



        #Then we save it to a file called the_new.yaml
        with open('the_new.yaml', 'w') as f:
            data2 = yaml.dump(data, f)
            print(data2)
            print(type(data2))


if __name__ == '__main__':
    main(sys.argv[1:])

最终目标是对数据进行一些转换,但在这个问题中,我想问一些更基本的问题。在上面的脚本中,没有发生任何转换

但是,在查看输出时,数据发生了变化。例如 file_base.yaml 有

first_data: # Required.
  type: ad
  class_names: ["hello",
            "dog",
            "cat",
            "lion",   
            "human"]

但是 the_new.yaml 有

first_data: 
      class_names: 
          -"hello"
          -"dog"
          -"cat"
          -"lion"   
          -"human"
      type: ad

如您所见,存在两个问题:

  • 田野乱了
  • 数组从[ one, two,three] 变为使用“-”

我该如何纠正这个问题?

【问题讨论】:

    标签: python pyyaml


    【解决方案1】:

    这是因为自动排序和 yaml 应用的样式。

    要防止排序,请将sort_keys 设置为False,对于样式,您可以将default_flow_style 设置为None

    filecontent = {"second_var": 45, "array": [1,2,3]}
    print(yaml.dump(filecontent))
    >> array:        
    >> - 1
    >> - 2
    >> - 3
    >> second_var: 45
    
    print(yaml.dump(filecontent, sort_keys=False, default_flow_style=None))
    >> second_var: 45
    >> array: [1, 2, 3]
    

    【讨论】:

    • @aasmpro:有时代码 sn-p 可以说明一切。但是感谢您使它完美:)也发现了其他主题,但它并没有完全重复恕我直言..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2023-04-06
    • 2011-04-05
    • 2014-10-04
    • 1970-01-01
    相关资源
    最近更新 更多