如何多次替换两个分隔符/字符串之间的唯一字符串

时间:2018-12-12 00:23:29

标签: python string replace substring between

我正在浏览文件夹/目录并阅读所有文件,检查是否有特定标签,然后仅在特定字符串介于两个特定字符串/标签之间时才多次替换特定字符串。 这是文本文件的示例:

START $YES
N1 000 001 002
N2 TAG#1 004 008
N3 This is an apple
N4 006 005 003
(( TAG#2 ))
N5 This is an apple

我想要一个可以打开文件,检查START $YESSTART $NO并在This is an apple之间将字符串There is no apple替换为TAG#1的解决方案和TAG#2(仅当存在START $YES时)。我希望原始文件不受影响(使用fileinput库创建新文件或创建备份)。

目前我无法发布python代码,但是当我回到办公桌时会使用尝试的代码更新这篇文章。

1 个答案:

答案 0 :(得分:2)

import shutil

def func(srcname, dstname):
    replace = False
    with open(srcname) as srcfile:
        with open(dstname, 'w+') as dstfile:
            line = srcfile.readline().strip()
            if "START $NO" in line:
                srcfile.seek(0)
                shutil.copyfileobj(srcfile, dstfile)
                return
            while line:
                if "TAG" in line and not replace:
                    replace = True
                if "TAG" in line and replace:
                    replace = False
                if replace and "This is an apple" in line:
                    line = line.replace("This is an apple", "There is no apple")
                dstfile.write(line)
                line = srcfile.readline().strip()