搜索并替换以文件中的特定字符串开头的特定行 [英] Search and replace specific line which starts with specific string in a file

查看:170
本文介绍了搜索并替换以文件中的特定字符串开头的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是打开一个属性文件并更新文件,出于更新目的,我需要搜索存储URL信息的特定字符串.为此,我在python中编写了以下代码:

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.

我们非常感谢您的帮助

文件内容示例:

# ***********************************************
# 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)

该脚本将input_file_name的每一行复制到output_file_name中,除了要更改的行.

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

这篇关于搜索并替换以文件中的特定字符串开头的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆