简体   繁体   中英

Search substring in line and then replace that line in text file

I am trying to write script that will first make a backup of the text file, then open it and search for line with specified string/sub string and then replace that line with new string/line.

To be more precise, this would be a file with values for some system options, and i want my script to find specific option and change it's current value.

So far i have this but it will only add new value to existing one, it will not replace it. Would appreciate the help.

import os
import shutil

shutil.copy2('C:/file_location/values.txt', 'C:/file_location/values.txt.backup')

with open('C:/file_location/values.txt') as values: 
  updated_values = values.read().replace('SystemOption', 'SystemOption = 1')

with open('C:/file_location/values.txt', "w") as new_values:
    new_values.write(updated_values)

SystemOption = 0 after i run script i get: SystemOption = 0 = 1

Desired effect after script is run is: SystemOption = 1

So i want to change from 0 to 1.

Problem is that in file the value can be either 0 or 1, so that is why i want to change entire line to be sure that value is 1 after script.

You can try using re module in python

with open('C:/file_location/values.txt') as values: 
    updated_values = values.read()
    updated_values = re.sub('SystemOption = 0', 'SystemOption = 1',updated_values)
import shutil

shutil.copy2('C:/file_location/values.txt', 'C:/file_location/values.txt.backup')

with open('C:/file_location/values.txt') as values:
    updated_values = values.read()
    if 'SystemOption' in updated_values:
        updated_values = updated_values.replace('SystemOption = 0', 'SystemOption = 1', 1)

with open('C:/file_location/values.txt', "w") as new_values:
    new_values.write(updated_values)

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