我正在Python 3上用Flask编写脚本。我有一台服务器,要求输入通常为多行的输入。然后,我接受该输入并将其写入文件:
@app.route('/editor',methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
result = request.form
print(request)
global file
file = result['script']
f = open(file, "r+")
contents = f.read()
f.close()
return render_template("result.html",result = result, file = file, cont = contents)
在此代码^中,我从输入表单中获取文件名,然后使用Flask模板:
<!doctype html>
<html>
<title>File Editor</title>
<body>
Editor:
<form action = "http://192.168.#.###:5000/save" method = "POST" id="form">
<textarea name="script" form="form" rows="10" cols="100">{{cont}}</textarea>
<p><input type = "submit" value = "Save" /></p>
</form>
</body>
</html>
此^重定向到保存路径
@app.route('/save',methods = ['POST', 'GET'])
def save():
contents = request.form
contents = contents.items()
ope = open(file, 'w+')
i = ''
for key, value in contents:
i = value
print(i)
i.replace('\n', '')
ope.write(i)
ope.close()
return redirect("/", code=302)
但是当我打开它编辑的文件时,行数比预期的要多(它之间添加了空行)。如果两个单词之间有一行,则为3;如果有2行,则为5;如果没有行,则为1。有什么想法吗?