简体   繁体   中英

How to insert a set of text to a particular line number of a file using Python

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在此处输入图像描述

After在此处输入图像描述

Does anyone know how to get this requirement done?

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] ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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