def make_file():
read_file = r'C:Users~Desktopsample.yml'
write_file = r'C:Users~Desktopsample_out.yml'
f = open(read_file, 'r')
lst = [line for line in f]
f.close()
ports = 'ports:n'
for index in range(len(lst)):
if "system_frontend:" in lst[index]:
count_spaces = len(lst[index+1]) - len(lst[index+1].lstrip(' '))
lst.insert(index+1, ports)
lst[index+1] = lst[index+1].rjust(count_spaces)
# lst.insert(index+1, " "*count_spaces + ports + " "*count_spaces + "- "0.0.0.0:5000:80"n") ## Did it this way, but it's not the best option.
with open(write_file, 'w', encoding='utf-8') as file:
for line in lst:
file.write(line)
The task is to place a certain amount of spaces in needed line(before str ‘ports:’, so it would look like ‘ ports:’).
fragment from .yml
services:
system_frontend:
image: ${DOCKER_REGISTRY}/frontend:${CONTAINER_VERSION}
logging: *id001
environment:
SSL_CERTIFICATE: ${SSL_CERTIFICATE:-}
SSL_CERTIFICATE_KEY: ${SSL_CERTIFICATE_KEY:-}
ENABLE_CORS: ${ENABLE_CORS:-}
FRONTEND_URL: ${FRONTEND_URL:-}
METRICS_PUSHGATEWAY: ${METRICS_PUSHGATEWAY:-}
volumes:
- ssl-volume:/etc/nginx/ssl
networks:
system_network: null
restart: unless-stopped
depends_on:
- webapi
Can’t succeed.
3
Answers
I think this is what you are trying to achieve. The main difference between your code and this is I added a break statement so the loop doesn’t keep performing actions after the target line has been found.
Please note that there are better ways to work with yaml files. Check out
pyyaml
in PyPi.output
I’m guessing that you are trying to alter
docker-compose.yaml
to add ports.There’s 2 options, you can either do it the hard way by processing text, or use
yaml.safe_load
to process the contentHere’s my take on how you can do it. Give it a try and see if it fits your needs
You insert a line while loop through it, you should leave the original lines intact and use another list to store output, this is what I would do: