繁体   English   中英

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

[英]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')

此代码始终删除我的 txt 文件中的所有行。 而且我有 unicode 和“input() 已经处于活动状态”错误。

这是执行此操作的正确方法吗? 我必须使用 python 2.6

您的代码将始终删除所有行,因为在这两种情况下,即当存在 search_line 和不存在 search_line 时,您都不会将行写回文件。

请检查以下带有注释的代码。

@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