簡體   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