Search and replace specific line which starts with specific string in a file
<p>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:</p>

<pre><code>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)
</code></pre>

<p>after executing the program i am not able to update the properties file.</p>

<p>Any help is highly appreciated</p>

<p>Sample Content of file:</p>

<pre><code># ***********************************************
# 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
</code></pre>

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

<pre><code>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)
</code></pre>

<p>That script copy every line of <code>input_file_name</code> into <code>output_file_name</code> except the lines that you want to change.</p>

python file search replace