Home > Enterprise >  Tempfile not found when finishing function
Tempfile not found when finishing function

Time:10-28

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'

CodePudding user response:

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'
        )
  • Related