python - 如何在 Flask 中将数据写入文本文件?

标签 python file flask server writetofile

我们的目标是将名为“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/

相关文章:

python - 为什么不能在 Python 中的 for 循环之前使用分号?

c# - FileInfo.CopyTo 返回 ArgumentException :

file - 如何为 MP4 文件创建缩略图系统

python - Flask/Heroku/Redis/RQ 内部服务器错误

python - 如何创建具有多个分类特征的SVM?

python - 使用 selenium python 显示等待时间 WebDriverWait

python - 具有多个返回值的模拟 python 函数

c# - File.Move原子操作

python - Python Flask 中 ssl_context 选项的区别

python - Flask 的子域?