I am trying to find "AAXX" and add the word "Hello" two lines above:
Input:
111
222
AAXX
333
444
AAXX
555
666
AAXX
Output:
Hello
111
222
AAXX
Hello
333
444
AAXX
Hello
555
666
AAXX
I have managed to insert only one "Hello" two lines before the first "AAXX" by using the code below, but I cannot make it loop through the file and do the same for all "AAXX" matches.
import os
with open(os.path.expanduser("~/Desktop/test.txt"), "r+") as f:
a = [x.rstrip() for x in f]
for i, item in enumerate(a):
if item.startswith("AAXX"):
a.insert(i-2,"Hello")
break
index += 1
# Go to start of file and clear it
f.seek(0)
f.truncate()
# Write each line back
for line in a:
f.write(line + "\n")
So far, I get:
Hello
111
222
AAXX
333
444
AAXX
555
666
AAXX
Can you try the following:
with open('test.txt', 'r') as infile:
data = infile.read()
final_list = []
for ind, val in enumerate(data.split('\n')):
final_list.append(val)
if val == 'AAXX':
final_list.insert(-3, 'HELLO')
# save the text file
with open('test.txt', 'w') as outfile:
data = outfile.write('\n'.join(final_list))
Output:
HELLO
111
222
AAXX
HELLO
333
444
AAXX
HELLO
555
666
AAXX