Reputation: 295
I am walking through a folder/directory and reading all files, checking if there is a certain tag, then replacing a specific string multiple times only when it is in between two certain strings/tags. Here is an example of the text files:
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
I would like a solution that can open the files, check if START $YES
or START $NO
, and replace the string This is an apple
into There is no apple
in between TAG#1
and TAG#2
only if START $YES
is present. I would prefer the original file to be left unaffected (create a new file or create a backup using the fileinput
library).
I cannot post my python code at the moment, but I will update this post when I am back at my work desk with the code that I have attempted.
Upvotes: 0
Views: 109
Reputation: 603
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()
Upvotes: 2