我正在浏览文件夹/目录并阅读所有文件,检查是否有特定标签,然后仅在特定字符串介于两个特定字符串/标签之间时才多次替换特定字符串。 这是文本文件的示例:
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 $YES
或START $NO
并在This is an apple
之间将字符串There is no apple
替换为TAG#1
的解决方案和TAG#2
(仅当存在START $YES
时)。我希望原始文件不受影响(使用fileinput
库创建新文件或创建备份)。
目前我无法发布python代码,但是当我回到办公桌时会使用尝试的代码更新这篇文章。
答案 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()