1. 程式人生 > >python操作yaml

python操作yaml

1. 安裝PyYAML

pip install PyYAML

2. 載入yaml檔案

直接使用yaml.load()函式

demo.yml :

kind: Deployment
apiVersion: apps/v1
metadata:
  name: podinfo
  namespace: yaml-demo
spec:
  replicas: 1
  selector:
    matchLabels:
     app: podinfo
  template:
    metadata:
      labels:
        app: podinfo
    spec:
      containers:
      - name: podinfod
        image: quay.io/stefanprodan/podinfo:0.3.0
        ports:
        - containerPort: 9898
import yaml
import json

result = yaml.load(open('demo.yml'))
print json.dumps(result, indent=2)

輸出 :

{
  "kind": "Deployment",
  "spec": {
    "replicas": 1,
    "template": {
      "spec": {
        "containers": [
          {
            "image": "quay.io/stefanprodan/podinfo:0.3.0",
            "name": "podinfod",
            "ports": [
              {
                "containerPort": 9898
              }
            ]
          }
        ]
      },
      "metadata": {
        "labels": {
          "app": "podinfo"
        }
      }
    },
    "selector": {
      "matchLabels": {
        "app": "podinfo"
      }
    }
  },
  "apiVersion": "apps/v1",
  "metadata": {
    "namespace": "yaml-demo",
    "name": "podinfo"
  }
}

3. 持久化dict到yml檔案

使用yaml.safe_dump()函式

import yaml

d = {
  "kind": "Deployment",
  "spec": {
    "replicas": 1,
    "template": {
      "spec": {
        "containers": [
          {
            "image": "quay.io/stefanprodan/podinfo:0.3.0",
            "name": "podinfod",
            "ports": [
              {
                "containerPort": 9898
              }
            ]
          }
        ]
      },
      "metadata": {
        "labels": {
          "app": "podinfo"
        }
      }
    },
    "selector": {
      "matchLabels": {
        "app": "podinfo"
      }
    }
  },
  "apiVersion": "apps/v1",
  "metadata": {
    "namespace": "yaml-demo",
    "name": "podinfo"
  }
}
result = yaml.safe_dump(d, encoding='utf-8', allow_unicode=True, default_flow_style=False)
open('demo.yml', 'w').write(result)

demo.yml :

apiVersion: apps/v1
kind: Deployment
metadata:
  name: podinfo
  namespace: yaml-demo
spec:
  replicas: 1
  selector:
    matchLabels:
      app: podinfo
  template:
    metadata:
      labels:
        app: podinfo
    spec:
      containers:
      - image: quay.io/stefanprodan/podinfo:0.3.0
        name: podinfod
        ports:
        - containerPort: 9898