Beka Tomashvili
Beka Tomashvili

Reputation: 2301

flask to write data into file

I have problem to write data into file from my flask developments server (win7),

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

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

 return render_template('index.html')

Why this don't works in flask ?

Upvotes: 4

Views: 28604

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251041

You should either flush the output to the file or close the file because the data may still be present in the I/O buffer.

Even better use the with statement as it'll automatically close the file for you.

with open("test.txt", "w") as fo:
   fo.write("This is Test Data")

Upvotes: 16

sakine Tunc
sakine Tunc

Reputation: 11

@app.route('/')
def main():
    fo= open("test.txt", "w")
    filebuffer = ["brave new world"]
    fo.writelines(filebuffer)
    fo.close()
    return render_template('index.html')

Upvotes: 1

Miguel Grinberg
Miguel Grinberg

Reputation: 67509

@Ashwini's answer is likely correct, but I wanted to point out that if you are writing to a file to have a logfile, then you should use Flask's support for logging instead. This is based on Python's logging module, which is very flexible. Documentation here.

Upvotes: 1

Related Questions