Araz Araz - 1 month ago 20
YAML Question

Split a YAML file in two separate files

I'm trying to split a YAML file in two different files such as below:

def yaml_loader():
try:
with open("test.yaml", "r") as stream:
data = yaml.load(stream)
for workload in data:
with open(workload['workload']['name'] + '.yaml', 'a') as outfile:
yaml.dump(workload, outfile)
except yaml.YAMLError as out:
print(out)


YAML:

- workload:
name: c1
param:
p1: 1
p2: 2

- workload:
name: c2
param:
p1: 30
p2: 200


But in the output both files are missing
-
for YAML syntax.

workload:
name: c1
param:
p1: 1
p2: 2


How can I fix this?

Answer

as @Ignacio Vazquez-Abrams said:

def yaml_loader():
  try:
    with open("test.yaml", "r") as stream:
       data = yaml.load(stream)
       for workload in data:
         with open(workload['workload']['name'] + '.yaml', 'a') as outfile:
              # if you put the variable "workload" in a list, you get the '-' in the yaml, as it denotes a list item.
              yaml.dump([workload], outfile)
  except yaml.YAMLError as out:
    print(out)

in a yaml,

"- item: " denotes a list item, so without putting your output in a list, you wont get the "-"