简体   繁体   English

搜索并替换以文件中的特定字符串开头的特定行

[英]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. 我的要求是打开一个属性文件并更新该文件,出于更新目的,我需要搜索一个存储URL信息的特定字符串。 For this purpose i have written the below code in python: 为此,我在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. 该脚本将您要更改的行之外的input_file_name每一行复制到output_file_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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