Q:

Writing a line in a file when finding a keyword

I am trying to make a function which writes a line when it finds some text inside a file. 
Example: it finds "hello" in a .txt file so then writes "Hi!" in the following line. There is something else, i want it to write "Hi!" not the first time it finds "hello" but the second.
Here is what i have been trying, but i don't know if the idea is right. Any help?  
def line_replace(namefilein):
    print namefilein
    filein=open(namefilein, "rw")
    tag="intro"
    filein.read()
    for line in filein:
        if tag=="second" or tag=="coord":
            try:
                filein.write("\n\n %s" %(text-to-be-added))
                print line
            except:
                if tag=="coord":    
                    tag="end"
                else:
                    tag="coord"

        if "           text-to-find" in line:
            if tag=="intro":
                tag="first"
            elif tag=="first":
                tag="second"
    filein.close()

A:

You can use this code:
def line_replace(namefilein):

    new_content = ''
    first_time = False
    with open(namefilein, 'r') as f:
        for line in f:
            new_content += line
            if 'hello' in line:
                if first_time:
                    new_content += 'Hi!' + '\n'
                else:
                    first_time = True

    with open(namefilein, 'w') as f:
        f.write(new_content)

Look that I am using the with statement that in Python is a context manager, so it means, in this case, when the block of code has executed, then the file will be closed automatically.
Let's supposed you have a file my_file.txt which contents is:
hello
friend
this
is
hello

And let's say your file is in the same directory than the python file that has your code, so calling:
line_replace('my_file.txt')

will produce the following output:
hello
friend
hello
Hi!
is

