Search code examples
pythonpython-re

Python replace text value regular expression


Is it possible to just replace a specific text's value in a file python? The below code replaces the string however I could'nt find a way to replace only the project_id or project_name's value.

import re 

def replace():
    with open("/Users/test/file.txt", "r") as sources:
        lines = sources.readlines()
    with open("/Users/test/file.txt", "w") as sources:
        for line in lines:
            sources.write(re.sub(r"Settings", 'Project_settings', line))

    
replace()

file.txt

Settings
######################
project_id = "468324678997"
project_name = "test"

output:

Project_settings
######################
project_id = "468324678997"
project_name = "test"

I would like to replace project_name's value to "abc"

Desired output: file.txt

Settings
######################
project_id = "468324678997"
project_name = "abc"

Solution

  • I suggest using a dictionary of config overrides, not regex

    This way, you are not accidentally replacing all matching text

    def replace(file, overrides):
        with open(file, "r") as sources:
            lines = sources.readlines()
        with open(file, "w") as sources:
            # skip the header rows
            next(lines)
            next(lines)
            for line in lines:
                config_key = line.split(' = ')[0]
                if config_key in overrides:
                    sources.write('{} = {}\n'.format(config_key, overrides[config_key]))
    
    overrides = {
      'project_name': 'abc'
    }
    replace("/Users/test/file.txt", overrides)
    

    There are likely better Python libraries that can read property files and allow you to override specific values