当我尝试写入某个文件时,会删除我文件中的所有内容,除了我试图替换的字样。
这是我的代码:
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)
这是我的文本文件:
#######
Address 192.168.0.3
Address 192.168.0.1 <--- I'm reading this
######
##############
########
Network 123.123.0.1 <---- I'm reading this
运行代码后,例如,我为192.168.0.1
替换1.1.1.1
,为123.123.0.1
替换0.0.0.0
我得到了这个:
Address 1.1.1.1
Network 0.0.0.0
你可以看到删除除了我替换之外的所有内容。我想得到这样的东西:
#######
Address 192.168.0.3
Address 1.1.1.1
######
##############
########
Network 0.0.0.0
所以我的应用程序不应该替换我想要替换的行。
答案 0 :(得分:3)
您只是将替换的行添加到您编写的列表中。
正如我在上一个问题中所说的那样,缩进新行,如果它不清楚,请附加未替换的行。
if address[cur_addr] in line:
# replace
new_var.append(new_line)
else:
# keep
new_var.append(line)