简体   繁体   English

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

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

Here is my yaml file这是我的 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

Here is my list of hosts这是我的主机列表

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

I am trying to write a program/script that takes host.yaml and host.list as input and if hosts in the host.list matches hosts in the host,yaml it should edit the yaml and remove those hosts.我正在尝试编写一个程序/脚本,将host.yamlhost.list作为输入,如果 host.list 中的主机与主机yaml中的主机匹配,它应该编辑 yaml 并删除这些主机。

In the above scenario python write_to_yaml.py host.yaml host.list should write below to yaml file.在上面的场景中python write_to_yaml.py host.yaml host.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

Please forgive me if this is a silly question, I am very very new to Python.如果这是一个愚蠢的问题,请原谅我,我是 Python 的新手。

You can do it by first installing pyyaml via:您可以通过以下方式首先安装pyyaml来完成此操作:

pip install pyyaml

And then you can use the library to read and write your yaml files like so:然后您可以使用该库来读取和写入您的 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM