Search and Replace in a Text File In Flask
<p>I want to search and replace in a text file in flask. </p>

<pre><code>@app.route('/links', methods=['POST'])
def get_links():
    search_line= "blah blah"
    try:
        for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt')):
        x = line.replace(search_line,
                           search_line + "\n" + request.form.get(u'query'))

    except BaseException as e:
        print e

    return render_template('index.html')
</code></pre>

<p>This code always deletes all lines in my txt file. And I have unicode and "input() already active" erros. </p>

<p>Is this a correct way to do this? I have to work with python 2.6</p>

<p>Your code will always delete all lines since you are not writing lines back to files in both case i.e when search_line is present and when search_line is not present.</p>

<p><strong>Please check the below code with comments inline.</strong></p>

<pre><code>@app.route('/links', methods=['POST'])
def get_links():
    search_line= "blah blah"
    try:
        for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt'),inplace=1):
            #Search line
            if search_line in line:
                    #If yes Modify it
                    x = line.replace(search_line,search_line + "\n" + request.form.get(u'query'))
                    #Write to file
                    print (x)
            else:
                #Write as it is
                print (x)

    except BaseException as e:
        print e

    return render_template('index.html')
</code></pre>

python flask