'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 enter image description here

After enter image description here

Does anyone know how to get this requirement done?



Solution 1:[1]

With a server.rb like

require 'sinatra'

set :public_folder, __dir__ + '/static'

get '/' do
  erb :index
end

A views/index.erb like

<link rel="stylesheet" type="text/css" href="/css/stylesheet.css">

Hi!

And your stylesheet in static/css/stylesheet.css it should work, the important bit you may be missing is setting the public folder.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 javiyu