Reputation: 356
I'm reading a such yaml file in python:
- test:
name: test1
param:
p1: v1
p2: v2
First I parse the file, then I apply some changes to it, and finally I dump it into multiple files.
def read_test():
with open('file.yaml', "r") as stream:
test = yaml.load(stream)
def write_test(config):
with open('test.yaml', 'w') as outfile:
yaml.dump(config, outfile, default_flow_style=False)
This is the output I get:
test:
name: test1
param:
p1: localhost:3000
p2: ../test/run.sh
But I expect this:
- test:
name: test1
param:
p1: localhost:3000
p2: ../test/run.sh
This is how I apply changes:
def split_test():
try:
tests = read_test()
for config in tests:
write_test(config)
except yaml.YAMLError as out:
print(out)
This function changes the final output's syntax. Any help?
Upvotes: 1
Views: 626
Reputation: 39688
There is no error here, your code is behaving exactly how you tell it to.
tests = read_test()
Okay, you read the original file and store the result in tests
.
for config in tests:
Now you iterate over the content of the original file. Which is a YAML sequence, so it is fine to iterate over it.
write_test(config)
Some remarks here:
write_test
always writes the same file, this will overwrite test.yaml
again and again for each config item.config
contains only the value of a list item, of course the list itself is not part of the YAML that is written.To get the output you want, simply replace these two lines:
for config in tests:
write_test(config)
with:
write_test(tests)
Note: Based on the naming of your functions, you want to split the file into multiple files. However, in the question's description, you describe that you only want to load it, modify it and then dump it again. You should probably be more clear in describing what you want to do.
Upvotes: 1