如果它们与列表 python 中的项目匹配,则从 yaml 文件中删除值

remove from values from yaml file if they match items in list python

这是我的 yaml 文件

cat host.yaml
list1:
 - host-1
 - host-2
 - host-3
 - host-4
list2:
 - host-5
 - host-6
 - host-7
 - host-8
list3:
 - host-9
 - host-10
 - host-11
 - host-12
list4:
 - host-13
 - host-14
 - host-15
 - host-16

这是我的主机列表

cat host.list
host-1
host-5
host-7
host-11
host-16

我正在尝试编写一个 program/script,它将 host.yamlhost.list 作为输入,如果 host.list 中的主机与 host 中的主机匹配,yaml 它应该编辑 yaml 并删除这些主机。

在上面的场景中pythonwrite_to_yaml.pyhost.yamlhost.list应该写在下面的yaml文件中。

cat host.yaml
list1:
 - host-2
 - host-3
 - host-4
list2:
 - host-6
 - host-8
list3:
 - host-9
 - host-10
 - host-12
list4:
 - host-13
 - host-14
 - host-15

如果这是一个愚蠢的问题,请原谅我,我对 Python 非常陌生。

您可以先安装 pyyaml 通过:

pip install pyyaml

然后您可以像这样使用该库来读写您的 yaml 文件:

import yaml

output = {}
host_set = []

# get list of hosts to exclude
with open(r'host.list') as file:
    hosts = yaml.load(file, Loader=yaml.FullLoader)
    host_set = set(hosts.split(" "))

# read host.yaml
with open(r'host.yaml') as file:
    documents = yaml.full_load(file)

    for l, hosts in documents.items():
        output[l] = list(set(hosts) - host_set) # remove items from the read in list of hosts

# write to file
with open(r'output.yaml', 'w') as file:
    documents = yaml.dump(output, file)