0

I have this simple program

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:])

The final objective is to do some transformations of the data, but in this question I want to ask something more basic. In the script above, no transformation is happening.

However, when looking at the output, the data has changed. For example file_base.yaml has

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

but the_new.yaml has

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

As you can see there are two problems:

  • The fields are in disorder
  • The arrays go from [ one, two,three] to using "-"

How can I correct this?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150

1 Answers1

1

that happens because of auto sort and styles that yaml applies to that.

to prevent sort, set sort_keys to False, for styles you can set default_flow_style to 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
  • 554
  • 9
  • 21
araisch
  • 1,727
  • 4
  • 15
  • @aasmpro: Sometimes a code snippet tells everything. But thanks for make it perfect :) Found that other topic as well, but it's not completely duplicated imho.. – araisch Aug 30 '21 at 09:32