Home > Mobile >  YAML: dump_all saves an empty file
YAML: dump_all saves an empty file

Time:12-29

I am trying to open a yaml file, update a value and save it. I have followed many examples already provided on stackoverflow, but it still doesn't work.

My code: import yaml

def update(x:int):
    with open("fileWithValues.yaml", "r") as yaml_file:
        try:
            docs=yaml.load_all(yaml_file, Loader=yaml.SafeLoader)
            for doc in docs:
                for key, value in doc.items():
                    if value == "city":
                        doc["year"]["value"] = x
                        break

            with open("fileWithValues.yaml", 'w') as yaml_file:
                yaml.dump_all(docs, yaml_file, default_flow_style=False)
        except yaml.YAMLError as exc:
            print(exc)

As said, to create the code, I have followed several examples from stackoverflow. But still, after executing the code it seems that it is opening the file to write in it but it leaves it empty. To summarize, the first part where I read the file works. The part where it is supposed to dump all the documents doesn't. It is not throwing any exception or error message. It just saves an empty file.

Additional info: the file I am reading contains two documents. And the value I update is in the second one.

Update: example file used to get the first data

---
apiVersion: v1
kind: Service
metadata:
  name: aa
  labels:
    app: aa
    service: aa
spec:
  selector:
    app: aa
  ports:
  - name: tcp-send
    port: 9000
---
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: capture-v1
  labels:
    app: aa
    version: v1
spec:
  replicas: 5
  selector:
    matchLabels:
      app: aa
      version: v1
  template:
    metadata:
      labels:
        app: aa
        version: v1
    spec:
      containers:
      - name: aa
        image: someimage:0.3
        ports:
          - name: tcp-send
            containerPort: 9000
        volumeMounts:
        - name: bb-aa
          mountPath: /etc/localtime
      volumes:
        - name: bb-aa
          hostPath:
            path: /path/
      nodeSelector:
        kubernetes.io/hostname: serve3
...   

Target parameter to be changed is: 2nd document, spec, replicas

CodePudding user response:

Your with statements are nested, so you're opening the file in write mode while it is already open in read mode. Separate them like so:

def update(x:int):
    try:
        with open("fileWithValues.yaml", "r") as yaml_file:
            docs = list(yaml.load_all(yaml_file, Loader=yaml.SafeLoader))
        for doc in docs:
            for key, value in doc.items():
                if value == "city":
                    doc["year"]["value"] = x
                    break

        with open("fileWithValues.yaml", 'w') as yaml_file:
            yaml.dump_all(docs, yaml_file, default_flow_style=False)
    except yaml.YAMLError as exc:
        print(exc)
  • Related