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

时间:2016-09-08 08:44:09

标签: python file search replace

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

li{
flex-basis: 10%;
background:grey;
padding-left: 5px;
}

执行程序后,我无法更新属性文件。

非常感谢任何帮助

文件的示例内容:

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)

1 个答案:

答案 0 :(得分:2)

我很确定这不是最好的方法,但这仍然是一种方式:

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,但您想要更改的行除外。

相关问题