【问题标题】:Tempfile not found when finishing function完成功能时找不到临时文件
【发布时间】:2021-10-26 22:46:37
【问题描述】:

我正在尝试创建一个临时文件,写入它,然后从我的烧瓶应用程序中下载它。但是,我在完成该功能时收到了 FileNotFoundError。这是我的代码和收到的错误。提前致谢。

    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'

【问题讨论】:

  • 离开with块时,临时文件会被自动删除。
  • 这就是它“临时”的原因
  • 您认为tempfile 到底是什么意思?你认为应该持续多久?当您对临时文件使用with 语句时,您认为这意味着文件的持续时间是什么?
  • 当然,这就是为什么我尝试在 with 块中使用 send_file。我喜欢临时文件,因为它会自行删除。我不希望我的 PA 应用被 csv 淹没

标签: python flask backend python-3.7 temporary-files


【解决方案1】:

TemporaryFile 在询问名称属性时不返回有效的文件描述符。您可以使用NamedTemporaryFile 询问姓名。

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

另一种针对少量数据的简单解决方法如下:

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

【讨论】:

  • 谢谢!我现在在工作,回家后会用我的应用程序测试这些!
  • 我选择了 io.StringIO 路线,它有效!再次感谢!
猜你喜欢
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2014-01-07
  • 2020-01-07
  • 2013-07-10
  • 2013-08-27
相关资源
最近更新 更多