3

I have a text file that has some values as follows:

matlab.file.here.we.go{1} = 50
matlab.file.here.sxd.go{1} = 50
matlab.file.here.asd.go{1} = 50

I want the code to look for "matlab.file.here.sxd.go{1}" and replace the value assigned to it from 50 to 1. But I want it to be dynamic (i.e., later I will have over 20 values to change and I don't want to search for that specific phrase). I'm new to python so I don't have much information in order to search for it online. Thanks

I tried the following

file_path = r'test\testfile.txt'
file_param = 'matlab.file.here.we.go{1}'
changing = 'matlab.file.here.we.go{1} = 1'
with open(file_path, 'r') as f:
    content = f.readlines()
    content = content.replace(file_param , changing)
with open(file_path, 'w') as f:
    f.write(content)

but it didn't achieve what I wanted

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
Moe AKI
  • 33
  • 3
  • To be clear, the `matlab.file.here.we.go{}' => 'matlab.file.here.we.go{1} = '` stuff will stay the same, it's just `` that will change? – Edward Peters Nov 23 '22 at 15:15
  • Yes. Only "someNumber" will change, and it will only change after the equal sign – Moe AKI Nov 23 '22 at 15:23
  • How's your regex-fu? Mine's weak, but I think https://stackoverflow.com/questions/2763750/how-to-replace-only-part-of-the-match-with-python-re-sub has what you want – Edward Peters Nov 23 '22 at 15:24

1 Answers1

1

You can split on the equal sign. You can read and write files at the same time.

import os
file_path = r'test\testfile.txt'
file_path_temp = r'test\testfile.txt.TEMP'
new_value = 50
changing = 'matlab.file.here.we.go{1} = 1'
with open(file_path, 'r') as rf, open(file_path_temp, 'w') as wf:
    for line in rf:
        if changing in line:
            temp = line.split(' = ')
            temp[1] = new_value
            line = ' = '.join(temp)
        wf.write(line)

os.remove(file_path)
os.rename(file_path_temp, file_path)
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439