Home > front end >  How to insert a set of text to a particular line number of a file using Python
How to insert a set of text to a particular line number of a file using Python

Time:05-22

I am trying to write a python program that can input a set of text in dictionary format and also a line number. I need to add this set of text to a specific line number of a .yaml file.

I have a Kubernetes deployment.yaml file and I need my Python program to add the text from the dictionary to a particular line number (line 29, in between cpu: "500m" and volumeMounts:) in the deployment.yaml file.

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
        resources:
      requests:
        memory: "64Mi"
        cpu: "250m"
      limits:
        memory: "128Mi"
        cpu: "500m"
      volumeMounts:
      - name: ephemeral
        mountPath: "/tmp"
  volumes:
    - name: ephemeral
      emptyDir: {}

test.py

yaml_change={
  "change": '''
      tolerations:
      - key: "example-key"
        operator: "Exists"
        effect: "NoSchedule"
  '''
}

line_number = 29
yaml_modification = yaml_change['change']

with open('values.yaml', 'r') as FileRead:
    yaml_data = FileRead.readlines()
    yaml_data = yaml_data[line_number-2] yaml_modification
    print(yaml_data)

with open('values.yaml', 'w') as FileWrite:
    FileWrite.writelines(yaml_data)

When I run the python file, the text file in the dictionary gets added to the .yaml file. However, all the other contents are lost.

Before enter image description here

After enter image description here

Does anyone know how to get this requirement done?

CodePudding user response:

Try changing the line yaml_data = yaml_data[line_number-2] yaml_modification to

yaml_data.insert(line_number - 1, yaml_modification)

yaml_data is a list of all lines in the file. The list.insert(idx, obj) function inserts the object at a given position.

Your solution doesn't work because you are adding the content you want to add and the line before (yaml_data[line_number-2]).

  • Related