[英]How to read data from uploaded csv file and view it using django?
[英]Read the data of the CSV file uploaded from the user
我正在嘗試編寫一個Python / Flask腳本,將csv文件轉換為其他文件。 我已經開發了一個UI,以便用戶可以上傳CSV文件。 我很難弄清楚如何讀取從用戶上傳的CSV文件的數據。
@app.route('/import', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
if not file.filename:
errors.append("Please select a file!")
else:
...
data = [GET CSV DATA HERE]
process_data(data)
我如何從CSV文件中獲取數據,以便可以通過以下方法:
def process_data(file):
with open(file, 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
...
先感謝您!
首先,我將交換if語句邏輯。
if file.filename:
csv_file = request.files["file"]
data = [GET CSV DATA HERE]
process_data(data)
else:
errors.append("Please select a file!")
#You could also have elif before the else to ensure
#that the requirement is met
elif file.filename:
pass
僅當文件存在或已上傳時,這才有意義,才應嘗試讀取文件。 如果文件未上傳但有發布請求,例如有人上傳了錯誤的文件類型,這將導致錯誤,從而導致腳本/應用執行失敗。
該文件已經存在於請求中,但是她是一個簡單的示例,您應該可以輕松地考慮到目前為止的工作量。
https://www.pythoncircle.com/post/30/how-to-upload-and-process-the-csv-file-in-django/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.