将数据写入fi的Flask

2024-04-27 06:32:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法将数据从flask developments服务器(win7)写入文件

 @app.route('/')
 def main():

    fo = open("test.txt","wb")
    fo.write("This is Test Data")

 return render_template('index.html')

为什么这在烧瓶里不起作用?


Tags: 文件数据test服务器txtappflaskmain
3条回答

您应该flush文件的输出,或者close文件,因为数据可能仍然存在于I/O缓冲区中。

最好使用with语句,因为它会自动为您关闭文件。

with open("test.txt","wb") as fo:
   fo.write("This is Test Data")
@app.route('/')
def main():
    fo= open("test.txt", "w")
    filebuffer = ["brave new world"]
    fo.writelines(filebuffer)
    fo.close()
    return render_template('index.html')

@Ashwini的答案很可能是正确的,但我想指出的是,如果您正在向一个文件写入日志文件,那么您应该使用Flask的支持来代替日志记录。这是基于Python的logging模块的,它非常灵活。文档here

相关问题 更多 >