Home > Software design >  Add text to the middle of a file based on a matching array
Add text to the middle of a file based on a matching array

Time:09-29

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")

CodePudding user response:

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 ~~greet\2", line))

print("\n".join(lines))

Prints:

Oh hi ~~greet there, Oh bye ~~greet there.
  • Related