我在我的Flask开发服务器(Win7)中写入数据到文件时遇到了问题。
@app.route('/')
def main():
fo = open("test.txt","wb")
fo.write("This is Test Data")
return render_template('index.html')
为什么这个在Flask中不起作用?
我在我的Flask开发服务器(Win7)中写入数据到文件时遇到了问题。
@app.route('/')
def main():
fo = open("test.txt","wb")
fo.write("This is Test Data")
return render_template('index.html')
如果数据仍然存在于I/O缓冲区中,您应该将输出flush
到文件或close
文件。
更好的方法是使用with
语句,它会自动为您关闭文件。
with open("test.txt", "w") as fo:
fo.write("This is Test Data")
"wb"
标志表示期望二进制数据而不是字符串,但在fo.write
中发送了一个字符串,导致以下错误:
TypeError:需要类似字节的对象,而不是'str'
。 我建议将"wb"
更改为"w"
以便将字符串写入文件。 - Helenawb
替换为 w
。 - Ashwini Chaudhary@Ashwini的回答可能是正确的,但我想指出,如果您正在写入文件以获得日志文件,则应使用Flask对日志记录的支持。这基于Python的logging
模块,非常灵活。文档在这里。
@app.route('/')
def main():
fo= open("test.txt", "w")
filebuffer = ["brave new world"]
fo.writelines(filebuffer)
fo.close()
return render_template('index.html')
fo.flush()
行。 - Ashwini Chaudhary