1

I have some files in YAML format, I need to find the text in the $title file and replace with what I specified. What the configuration file looks like approximately:

JoinGame-MOTD:
  Enabled: true
  Messages:
  - '$title'

The YAML file may look different, so I want to make a universal code that will not get any specific string, but replace all $title with what I specified

What I was trying to do:

import sys
import yaml

with open(r'config.yml', 'w') as file:
    
    def tr(s):
        return s.replace('$title', 'Test')

        yaml.dump(file, sys.stdout, transform=tr)

Please help me. It is not necessary to work with my code, I will be happy with any examples that can suit me

DorgZ
  • 13
  • 3

2 Answers2

2

Might be easier to not use the yaml package at all.

with open("file.yml", "r") as fin:
     with open("file_replaced.yml", "w") as fout:
         for line in fin:
             fout.write(line.replace('$title', 'Test'))

EDIT:

To update in place

with open("config.yml", "r+") as f:
    contents = f.read()
    f.seek(0)
    f.write(contents.replace('$title', 'Test'))
    f.truncate()
pistolpete
  • 968
  • 10
  • 20
0

You can also read & write data in one go. os.path.join is optional, it makes sure the yaml file is read relative to path your script is stored

import re
import os

with open(os.path.join(os.path.dirname(__file__), 'temp.yaml'), 'r+') as f:
    data = f.read()
    f.seek(0)
    new_data = data.replace('$title', 'replaced!')
    f.write(new_data)
    f.truncate()

In case you wish to dynamically replace other keywords besides $title, like $description or $name, you can write a function using regex like this;

def replaceString(text_to_search, keyword, replacement):
    return re.sub(f"(\${keyword})[\W]", replacement, text_to_search)

replaceString('My name is $name', '$name', 'Bob')
Robb216
  • 554
  • 4
  • 10