Add text to the middle of a file based on a matching array

Question:

I want to add text to the middle of a file if a word within an array is detected:

array:[hi,bye]

Please do not use find and replace.
A sentence from file.txt:

Oh hi there, Oh bye there.
New Sentence: Oh hi ~~greet there, Oh bye ~~greet there.

with open(file.txt,r) as f:
    line=f.readlines()
with open(file.txt,a) as f:
    if any(place in line for place in array):
        f.writelines("~~greet")
Asked By: user18774110

||

Answers:

Try re module:

import re

pat = re.compile(r"b(hi|bye)(s*)")
lines = []
with open("your_file.txt", "r") as f_in:
    for line in f_in:
        lines.append(pat.sub(r"1 ~~greet2", line))

print("n".join(lines))

Prints:

Oh hi ~~greet there, Oh bye ~~greet there.
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.