pythonbegineer pythonbegineer - 3 months ago 10
Python Question

Python - replace multiple lines in Python Flask help please

, I'm new with Python!

Hope you guys could help, 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()
if request.method =="POST":
word = request.form ['word']
words = request.form ['words']
filedata= None
rem = None
with open('line.txt','r') as f:
filedata =
rem =

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

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

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

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

if __name__ == '__main__':

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 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 }}">

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


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

Here's my output in client:
Here is my output

If someone could help I'll love that!
Thanks in advance!


Try doing this in your code:

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

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

No need to read and write the same content twice.