简体   繁体   中英

Search and Replace in a Text File In Flask

I want to search and replace in a text file in flask.

@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')

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

Is this a correct way to do this? I have to work with python 2.6

Your code will always delete all lines since you are not writing lines back to files in both case ie when search_line is present and when search_line is not present.

Please check the below code with comments inline.

@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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM