I am working through a large document and need to find 2 specific, identical blocks of lines in the doc and perform different edits on each block. Of note, I need to be able to find the blocks off a keyword, and then edit the line which contains the keyword as well as the previous line.
I have tried to put together code from previous questions such as: python how to write to specific line in existing txt file
An example document would be:
hundreds of lines of text
more lines
previous line1
search_term line1
previous line2
search_term line 2
more blocks of text
Here I want to find the two lines containing the search term, then edit them as well as their preceding lines.
below is a simplified example of the code I am trying with.
with open(end_file1, "r+") as f2:
with open(act_end1, "w+") as f3:
lines = f2.readlines()
def index_searched(lines, substring):
for i, s in enumerate(lines):
if search_item in s:
i = lineNUM
linei[1] = i
break
for i>lineNUM, s in enumerate(lines):
if search_item in s:
linei[2] = i
return -1
for line in lines:
if len(lines) > int(linei[1]):
line = lines[linei[1]]
previous = line[-1]
#do stuff
if len(lines) > int(linei[2]):
line = lines[linei[2]]
previous = line[-1]
#do stuff
I am getting an error for the part where I try to save linei[i] in the first loop. I am trying to use that to create linei[1] and linei[2] which would give the line #s the search string is found in. I also assume that once I fix that, the way I tried to define the previous lines will give me an error. Any advice there?