简体   繁体   English

在 Flask 中的文本文件中搜索和替换

[英]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.此代码始终删除我的 txt 文件中的所有行。 And I have unicode and "input() already active" erros.而且我有 unicode 和“input() 已经处于活动状态”错误。

Is this a correct way to do this?这是执行此操作的正确方法吗? I have to work with python 2.6我必须使用 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.您的代码将始终删除所有行,因为在这两种情况下,即当存在 search_line 和不存在 search_line 时,您都不会将行写回文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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