簡體   English   中英

如何使用 Python 將一組文本插入文件的特定行號

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

我正在嘗試編寫一個 python 程序,它可以輸入一組字典格式的文本以及一個行號。 我需要將這組文本添加到 .yaml 文件的特定行號。

我有一個 Kubernetes deployment.yaml 文件,我需要我的 Python 程序將字典中的文本添加到 deployment.yaml 文件中的特定行號(第 29 行,在 cpu: "500m"volumeMounts:之間)。

部署.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: {}

測試.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)

當我運行 python 文件時,字典中的文本文件被添加到 .yaml 文件中。 但是,所有其他內容都丟失了。

在此處輸入圖像描述

在此處輸入圖像描述

有誰知道如何完成這個要求?

嘗試將yaml_data = yaml_data[line_number-2]+yaml_modification行更改為

yaml_data.insert(line_number - 1, yaml_modification)

yaml_data是文件中所有行的列表。 list.insert(idx, obj)函數在給定位置插入對象。

您的解決方案不起作用,因為您正在添加要添加的內容和之前的行( yaml_data[line_number-2] )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM