简体   繁体   中英

Search and replace specific line which starts with specific string in a file

My requirement is to open a properties file and update the file, for update purpose i need to search for a specific string which stores the url information. For this purpose i have written the below code in python:

import os
owsURL="https://XXXXXXXXXXXXXX/"
reowsURL = "gStrOwsEnv = " + owsURL + "/" + "OWS_WS_51" + "/"
fileName='C:/Users/XXXXXXXXXXX/tempconf.properties'
if not os.path.isfile(fileName):
    print("!!! Message : Configuraiton.properties file is not present ")
else:
    print("+++ Message : Located the configuration.properties file")
    with open(fileName) as f:
         data = f.readlines()
         for m in data:
              if m.startswith("gStrOwsEnv"):
                  print("ok11")
                  m = m.replace(m,reowsURL)

after executing the program i am not able to update the properties file.

Any help is highly appreciated

Sample Content of file:

# ***********************************************
# Test Environment Details
# ***********************************************

# Application URL pointing to test execution
#gStrApplicationURL =XXXXXXXXXXXXXXXX/webservices/person
#gStrApplicationURL = XXXXXXXXXXXXXX/GuestAPIService/ProxyServices/

# FOR JSON
#gStrApplicationURL = XXXXXXXXXXXXXX

#SOAP_gStrApplicationURL =XXXXXXXXXXXXXXXXXXXXXXX
#(FOR WSDL PARSING)
version = 5
#v9
#SOAP_gStrApplicationURL = XXXXXXXXXXX/XXXXXXXXX/XXXXXXXXX/
#v5
SOAP_gStrApplicationURL = XXXXXXXXXXXXXXX/OWS_WS_51/
gStrApplicationXAIServerPath=
gStrEnvironmentName=XXXXXXXXX
gStrOwsEnv = XXXXXXXXXXXXXXXXXXXX/OWS_WS_51/
gStrConnectEnv = XXXXXXXXXXXXXXXXX/OWSServices/Proxy/
gStrSubscriptionKey =XXXXXXXXXXXXXXXXXXXXXX

I'm pretty sure that this is not the best way of doing that, but this is still one way:

with open(input_file_name, 'r') as f_in, open(output_file_name, 'w') as f_out:
    for line in f_in:
        if line.startswith("gStrOwsEnv"):
            f_out.write(reowsURL)
        else:
            f_out.write(line)

That script copy every line of input_file_name into output_file_name except the lines that you want to change.

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