简体   繁体   中英

How to search and replace a specific value in a line in Python

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 (ie, 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM