[英]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.我正在尝试编写一个 python 程序,它可以输入一组字典格式的文本以及一个行号。 I need to add this set of text to a specific line number of a .yaml file.我需要将这组文本添加到 .yaml 文件的特定行号。
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.我有一个 Kubernetes deployment.yaml 文件,我需要我的 Python 程序将字典中的文本添加到 deployment.yaml 文件中的特定行号(第 29 行,在 cpu: "500m"和volumeMounts:之间)。
deployment.yaml部署.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测试.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.当我运行 python 文件时,字典中的文本文件被添加到 .yaml 文件中。 However, all the other contents are lost.但是,所有其他内容都丢失了。
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 = yaml_data[line_number-2]+yaml_modification
行更改为
yaml_data.insert(line_number - 1, yaml_modification)
yaml_data
is a list of all lines in the file. yaml_data
是文件中所有行的列表。 The list.insert(idx, obj)
function inserts the object at a given position. list.insert(idx, obj)
函数在给定位置插入对象。
Your solution doesn't work because you are adding the content you want to add and the line before ( yaml_data[line_number-2]
).您的解决方案不起作用,因为您正在添加要添加的内容和之前的行( yaml_data[line_number-2]
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.