pythonbegineer pythonbegineer - 1 month ago 7
Python Question

Python - replace multiple lines in Python Flask

I'm new with Python!

I have a form where I'm reading and writing everything ok, the replace is working fine in the first input, but it's not working in my second input.

For example I have my word 1 = Toy, if I change it for "house" it overwrites my .txt very well, but if I do with my word 2 = house, nothing happens.

This is my code 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)


this is my .txt

wordone Toy
wordtwo house


this is my .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>


As word 1 is working, my only problem is with word 2..

Here's my output in client:

Here is my output

Answer

Try doing this in your code:

        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)

No need to read and write the same content twice.