我正在嘗試創建一個臨時檔案,寫入它,然后從我的 Flask 應用程式下載它.. 但是,我在完成該功能時收到 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'
uj5u.com熱心網友回復:
TemporaryFile當詢問 name 屬性時不回傳有效的檔案描述符。您可以使用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'
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339947.html
標籤:Python 烧瓶 后端 python-3.7 临时文件
