繁体   English   中英

如何在 Python 中编辑包含多个 YAML 文档的文件

[英]How to edit a file with multiple YAML documents in Python

我有以下 YAML 文件:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nodejs
  namespace: test
  labels:
    app: hello-world
spec:
  selector:
    matchLabels:
      app: hello-world
  replicas: 100
  template:
    metadata:
      labels:
        app: hello-world
    spec:
      containers:
      - name: hello-world
        image: test/first:latest
        ports:
        - containerPort: 80
        resources:
          limits:
            memory: 2500Mi
            cpu: "2500m"
          requests:
            memory: 12Mi
            cpu: "80m"
---
apiVersion: v1
kind: Service
metadata:
  name: nodejs
spec:
  selector:
    app: hello-world
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
      nodePort: 30082   
  type: NodePort

我需要使用 Python 编辑 YAML 文件,我尝试了下面的代码,但它不适用于包含多个 YAML 文档的文件。 你可以看到下图: 在此处输入图像描述

import ruamel.yaml

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.explicit_start =  True

with open(r"D:\deployment.yml") as stream:
   data = yaml.load_all(stream)

test = data[0]['metadata']
test.update(dict(name="Tom1"))
test.labels(dict(name="Tom1"))

test = data['spec']
test.update(dict(name="sfsdf"))

with open(r"D:\deploymentCopy.yml", 'wb') as stream:
    yaml.dump(data, stream)

您可以参考链接了解更多信息: Python: Replacing a String in a YAML file

“它不工作”不是很具体的问题描述。

load_all()产生每个文件,所以你通常会使用它:

for data in yaml.load_all(stream):
    # work on the data of each individual document

如果你想要一个可索引列表中的所有数据,就像你做的那样,你必须list()来列出生成的数据:

     data = list(yaml.load_all(stream))

如果您使用.load_all()加载可变data中的大量文档,您很可能不想将data转储到单个对象中(使用.dump() ),而是想使用.dump_all() ,因此您可以将每个data元素转储到单独的文档中:

with open(r"D:\deploymentCopy.yaml", 'wb') as stream:
    yaml.dump(data, stream)

ruamel.yaml无法区分是转储在其根部具有列表(即 YAML 序列)的数据结构还是转储应该放在不同文档中的数据结构列表。 所以你必须使用.dump()来区分。 .dump_all()

除此之外, yaml.org网站上的官方 YAML 常见问题解答指出,带有 YAML 文档的文件的推荐扩展名是.yaml 自从这成为推荐以来(16 年前,即至少自 2006 年 9 月以来),可能有一些项目没有更新。

我已经参考Anthon's Answer添加了完整的脚本

请找到以下脚本以供参考:

import ruamel.yaml

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.explicit_start =  True

with open(r"D:\deployment.yml") as stream:
    data=list(yaml.load_all(stream))

data[0]['metadata']['namespace']="namespace"
data[0]['metadata']['labels']['app']="namespace"
data[0]['spec']['template']['spec']['containers'][0]['name']="test"

data[1]['spec']['selector']['app']="test"

with open(r"D:\deploymentCopy.yml", 'wb') as stream:
    yaml.dump_all(data, stream)

暂无
暂无

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

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