我们的目标是将名为“inputed_email”的变量写入名为“test3.txt”的文本文件中。因为这是在服务器上进行的,所以我们需要确保该 Python 脚本可以访问该目录和文本文件。
@app.route('/', methods=['GET', 'POST'])
def my_form():
inputed_email = request.form.get("email")
if request.method == 'POST' and inputed_email:
# write to file
with open('/var/www/FlaskApp/FlaskApp/test3.txt', 'w') as f:
f.write(str(inputed_email))
return render_template('my-form.html', email=inputed_email)
return render_template('my-form.html')
但是,写入“test3.txt”的代码不起作用。运行时返回错误 500(内部服务器错误)。如有任何帮助,我们将不胜感激!
最佳答案
我的猜测是您没有指定正确的目录。如果 Flask 就像 Django,路径可能与应用程序运行时位于不同的位置。尝试打印 os.listdir() 以查看您所在的位置。
from os import listdir
@app.route('/', methods=['GET', 'POST'])
def my_form():
inputed_email = request.form.get("email")
if request.method == 'POST' and inputed_email:
print(listdir) ## print listdir python 2
# write to file
with open('/var/www/FlaskApp/FlaskApp/test3.txt', 'w') as f:
f.write(str(inputed_email))
return render_template('my-form.html', email=inputed_email)
return render_template('my-form.html')
如果它没有向控制台打印任何内容,则错误发生在行打印之前。
关于python - 如何在 Flask 中将数据写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50958510/