pythonbegineer pythonbegineer - 22 days ago 6
Python Question

Python - when I'm writing to a file deletes everything except the replaced word

Hi guys I need help please, when I'm trying to write to a file deletes everything in my file except the words I'm trying to replace..

here is my code:

app.route('/', methods=['POST'])
def writing():
address_1 = address1()
address_2 = network1()

try:
if request.method =="POST":
var1 = request.form ['addr1']
var2 = request.form ['addr2']

changeaddress = [var1, var2]
address = [address_1, address_2]
new_var = []
cur_addr = 0
new_line = None
with open('address.txt','r+') as file:
for line in file:
if address[cur_addr] in line:
new_line = line.replace(address[cur_addr], changeaddress[cur_addr] + "\n")
cur_addr += 1
new_var.append(new_line)

with open('address.txt','w') as file:
file.writelines(new_var)

except BaseException as e:
print e

return render_template('addr.html', var1=var1,var2=var2)


this is my text file :

#######
Address 192.168.0.3
Address 192.168.0.1 <--- I'm reading this
######
##############
########
Network 123.123.0.1 <---- I'm reading this


after runing the code for example I replace
192.168.0.1
for
1.1.1.1
and
123.123.0.1
for
0.0.0.0
I get this:

Address 1.1.1.1
Network 0.0.0.0


As you can see it deleting everything except what I replaced. I would like to get something like this:

#######
Address 192.168.0.3
Address 1.1.1.1
######
##############
########
Network 0.0.0.0


So my app should not replace the lines I want to replace.

Answer

You are only adding the replaced line to the list that you write.

As I said in a previous question, indent the new line, and in case it wasn't clear there, append the non-replaced line.

if address[cur_addr] in line:
    # replace 
    new_var.append(new_line)
else:
    # keep 
    new_var.append(line)