我在烧瓶中有一个应用,我在那里阅读两种颜色,但是当我尝试更换它时,它会删除我.txt文件中的所有内容,但是我试图替换的行。< / p>
这是我的python文件:
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)
这是我的文本文件:
/////
/////
/////
////
/////
/////////
color green
color green
正如你所看到的,我想要取代&#34;绿色&#34;黄色和其他&#34;绿色&#34;为红色,但这样做会删除每一个&#34; /&#34;在文件中只留下最后两行。
任何人都可以帮我解决这个问题吗? 提前致谢!!
答案 0 :(得分:2)
预期:
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])
您更改filedata
的第6行和第7行,再次打开/截断文件,然后只写两行。放下其余的。
在您的情况下,修复很简单。由于您已根据需要更改了行数组,因此只需回写整行,并根据您的更改进行修改。所以将最后一部分改为:
with open('line.txt','w') as f:
f.writelines(filedata)