Reputation: 35
I don't find an easy way to do this..
I have a large complex yaml file, I want to load it and write only a couple of the keys into a NEW yaml file.
So for example:
Existing:
a:
bsect:
thing: one
ab:
bbsect:
morething: more
thisone: dbname
ac:
ccc:
cccthing: here
bd:
bbb:
bbbthing: again
So I load the yaml file using import yaml and I load using: cfg = yaml.load(file) within a with open.
I want to create a NEW yaml file just with with cfg[ab] and cfg[thisone]
But when I create the yaml file using yaml.dump I obviously end up with the content of cfg[ab] and cfg[thisone] without the keys and it looks like this.
bbsect:
morething: more
dbname.
It makes sense but what is the best way to end up with a new yaml file that contains:
ab:
bbsect:
morething: more
thisone: dbname
I hope this makes sense.
Thanks in advance.
Upvotes: 2
Views: 232
Reputation: 6758
You can create a new blank config and write data to it.
x = '''
a:
bsect:
thing: one
ab:
bbsect:
morething: more
thisone: dbname
ac:
ccc:
cccthing: here
bd:
bbb:
bbbthing: again
'''
import yaml
cfg = yaml.load(x)
new_cfg = {}
new_cfg['ab'] = cfg['ab']
new_cfg['thisone'] = cfg['thisone']
yaml.dump(new_cfg, default_flow_style=False)
Output:
ab:
bbsect:
morething: more
thisone: dbname
Upvotes: 1