我们希望使用python从YAML文件中删除键和值,例如
- misc_props:
- attribute: tmp-1
value: 1
- attribute: tmp-2
value: 604800
- attribute: tmp-3
value: 100
- attribute: tmp-4
value: 1209600
name: temp_key1
attr-1: 20
attr-2: 1
- misc_props:
- attribute: tmp-1
value: 1
- attribute: tmp-2
value: 604800
- attribute: tmp-3
value: 100
- attribute: tmp-4
value: 1209600
name: temp_key2
atrr-1: 20
attr-2: 1从上面的示例中,我们想要删除整个属性,其中键名称与值匹配,例如,如果我们想删除名称: temp_key2删除后新创建的字典将如下所示:-
- misc_props:
- attribute: tmp-1
value: 1
- attribute: tmp-2
value: 604800
- attribute: tmp-3
value: 100
- attribute: tmp-4
value: 1209600
name: temp_key1
attr-1: 20
attr-2: 1发布于 2019-10-20 03:17:49
删除键-值对以获得所需的输出是不够的。
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open('input.yaml') as fp:
data = yaml.load(fp)
del data[1]['misc_props']
yaml.dump(data, sys.stdout)因为这给出了:
- misc_props:
- attribute: tmp-1
value: 1
- attribute: tmp-2
value: 604800
- attribute: tmp-3
value: 100
- attribute: tmp-4
value: 1209600
name: temp_key1
attr-1: 20
attr-2: 1
- name: temp_key2
atrr-1: 20
attr-2: 1您需要做的是删除作为YAML结构根的序列中的一项:
del data[1]
yaml.dump(data, sys.stdout)这就给出了:
- misc_props:
- attribute: tmp-1
value: 1
- attribute: tmp-2
value: 604800
- attribute: tmp-3
value: 100
- attribute: tmp-4
value: 1209600
name: temp_key1
attr-1: 20
attr-2: 1发布于 2019-10-20 01:54:49
你有没有试过使用yaml模块?
import yaml
with open('./old.yaml') as file:
old_yaml = yaml.full_load(file)
#This is the part of the code which filters out the undesired keys
new_yaml = filter(lambda x: x['name']!='temp_key2', old_yaml)
with open('./new.yaml', 'w') as file:
documents = yaml.dump(new_yaml, file)https://stackoverflow.com/questions/58466174
复制相似问题