Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to create a tempfile, write to it, then download it from my flask application.. however, i am receiving a FileNotFoundError when finishing the function. Here is my code & the error received. Thanks in advance.

    with tempfile.TemporaryFile (mode='w', newline="", dir=".", suffix='.csv') as csvfilenew:
        writer = csv.writer(csvfilenew, delimiter= ';')
        myClick()
        return send_file(str(csvfilenew.name), as_attachment=True, attachment_filename='cleanfile.csv')

FileNotFoundError: [Errno 2] No such file or directory: '/Desktop/bulk_final/10'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

TemporaryFile does not return a valid filedescriptor when asked for the name attribute. You can use NamedTemporaryFile to ask for the name.

from flask import send_file
import tempfile
import csv

@app.route('/download')
def download():
    with tempfile.NamedTemporaryFile(mode='w', newline='', dir='.', suffix='.csv') as csvfilenew:
        writer = csv.writer(csvfilenew, delimiter= ';')
        writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
        csvfilenew.flush()
        csvfilenew.seek(0)
        return send_file(csvfilenew.name,
            as_attachment=True,
            attachment_filename='cleanfile.csv'
        )

Another simple workaround for small amounts of data is as follows:

from flask import send_file
import csv
import io

@app.route('/download')
def download():
    with io.StringIO() as doc:
        writer = csv.writer(doc, delimiter= ';')
        writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
        doc.seek(0)
        return send_file(io.BytesIO(doc.read().encode('utf8')),
            as_attachment=True,
            attachment_filename='cleanfile.csv'
        )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...