Python - 在Python Flask中替换多行

时间:2016-10-23 20:08:25

标签: python python-2.7 flask

我是Python的新手!

我有一个表单,我在那里阅读和写入一切正常,替换在第一个输入中正常工作,但它在我的第二个输入中不起作用。

例如,我有我的话1 =玩具,如果我更改为" house"它很好地覆盖了我的.txt,但如果我用我的话2 =房子,那就什么都没发生。

这是我的代码Flask:

from flask import Flask,render_template,flash,request,redirect
import os
app = Flask(__name__)
from lines import word_one,word_two

@app.route('/', methods=['POST'])
def change_line():
    error= 'Cambios exitosos.'
    replace = word_one()
    replacetwo = word_two()
    try:
        if request.method =="POST":
            word = request.form ['word']
            words = request.form ['words']
            filedata= None
            rem = None
            with open('line.txt','r') as f:
                filedata = f.read()
                rem = f.read()

                filedata = filedata.replace(replace , word + "\n" )
                rem = rem.replace(replacetwo , words + "\n" )

            with open('line.txt','w') as f:
                f.write(filedata)
                f.write(rem)

    except BaseException as e:
        print e 
    return render_template('line.html')

@app.route('/')
def showLine():
    wordone = word_one()
    wordtwo = word_two()
    return render_template('line.html', wordone=wordone, wordtwo=wordtwo)


if __name__ == '__main__':
    app.run(debug=True)

这是我的.txt

wordone Toy
wordtwo house

这是我的.html

<form method="post" name="test">
                            <h4>Chaging Values with POST Method</h4>
                            <div class="col-sm-9">
                            <label class="col-sm-3 col-sm-3 control-label">word 1 : </label>
                            <input type="text" class="form-control" name="word" value="{{ wordone }}">
                            </div>
                            <div class="col-sm-9">
                            <label class="col-sm-3 col-sm-3 control-label">word 2 : </label>
                            <input type="text" class="form-control" name="words" value="{{ wordtwo }}">
                            </div>


                            <input type="submit" value="Save Changes!">


    </form>

由于单词1正在起作用,我唯一的问题是单词2 ..

这是我在客户端的输出:

Here is my output

1 个答案:

答案 0 :(得分:1)

尝试在您的代码中执行此操作:

        with open('line.txt','r') as f:
            filedata = f.read()
            filedata = filedata.replace(replace , word + "\n" )
            filedata = filedata.replace(replacetwo , words + "\n" )

        with open('line.txt','w') as f:
            f.write(filedata)

无需两次读取和写入相同的内容。