pythonbegineer pythonbegineer - 1 month ago 6
Python Question

Python replacing an specific word in a line

I have an aplication in flask , where I'm reading two colors, but when I try to replace them it deletes me everything in my .txt file but the lines that I'm trying to replace.

Here's my python file:

from flask import Flask,render_template,flash,request,redirect
import os
import sys
app = Flask(__name__)

def word_one():
with open('line.txt', 'r+') as f:
for i, line in enumerate(f):
if i == 6:
found_color = line.find('color')
if found_color != -1:
color_one = line[found_color+len('color:'):]
print ('Color_One: '), color_one
return color_one


def word_two():
with open('line.txt', 'r+') as f:
for i, line in enumerate(f):
if i == 7:
found_color = line.find('color')
if found_color != -1:
color_two = line[found_color+len('color:'):]
print ('Color_Two: '), color_two
return color_two

@app.route('/', methods=['POST'])
def change_line():
error= 'Sucessfull.'
first_color = word_one()
second_color = word_two()
try:
if request.method =="POST":
change_first_color = request.form ['first_color']
change_second_color = request.form['second_color']
filedata= None
with open('line.txt','r') as f:
filedata = f.readlines()

filedata[6] = filedata[6].replace(first_color , change_first_color + "\n" )
filedata[7] = filedata[7].replace(second_color , change_second_color + "\n" )

with open('line.txt','w') as f:
f.write(filedata[6])
f.write(filedata[7])


except BaseException as e:
print e
return render_template('line.html', error=error, change_first_color=change_first_color,
change_second_color=change_second_color)

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

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


this is my text file :

/////
/////
/////
////
/////
/////////
color green
color green


As you can see I want to replace "green" to yellow and the other "green" to red, but when doing so it deletes every "/" in the file leaving just the last 2 lines.

Can anyone help me with this problem? thanks in advance!!

Answer

that's expected:

    with open('line.txt','r') as f:
        filedata = f.readlines()

        filedata[6] = filedata[6].replace(first_color , change_first_color + "\n" )
        filedata[7] = filedata[7].replace(second_color , change_second_color + "\n" )

    with open('line.txt','w') as f:
        f.write(filedata[6])
        f.write(filedata[7])

You change lines 6 and 7 of filedata, you open/truncate the file again and just write both lines. droping the rest.

In your case, the fix is simple. Since you have changed the array of lines according to your need, just write back the full lines, modified with your changes. So change that last part into:

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