python - 使用 Flask 上传和读取 CSV 文件
问题描述
我目前正在制作一个程序来上传和读取 csv 文件。我在提交要上传的文件时抛出了一个关键错误,并且似乎无法弄清楚原因并希望得到一些帮助。在我尝试添加读取文件功能之前,它上传并保存了文件,但在那之后,它开始出现问题。错误是说“文件名”是一个关键错误,即使在我尝试读取文件之前它似乎工作正常。帮助或引导我走上正确的道路将不胜感激。非常感谢!
视图.py
from flask import render_template, request, redirect
from app import app
import os
import csv
@app.route('/', methods=["GET", "POST"])
def index():
data = []
if request.method == 'POST':
if request.files:
uploaded_file = request.files['filename'] # This line uses the same variable and worked fine
uploaded_file.save(os.path.join(app.config['FILE_UPLOADS'], uploaded_file.filename))
f = request.form['filename'] # This is the line throwing the error
with open(f) as file:
csv_file = csv.reader(file)
for row in csv_file:
data.append(row)
return redirect(request.url)
return render_template('index.html', data=data)
@app.route('/help')
def help():
return render_template('help.html')
app.config['FILE_UPLOADS'] = "C:\\Users\\Zachary\\Documents\\VSCode_Projects\\monday_webapp\\app\\static\\file\\uploads"
索引.html
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block body %}
<div class="jumbotron">
<h1 style='text-align: center'>Zach's Web Application</h1>
</div>
<div>
<p class="lead">Upload a csv file to view its data.</p>
<form method="POST" enctype="multipart/form-data" action="/">
<input type="file" id="myFile" name="filename" accept=".csv">
<input type="submit">
</form>
</div>
<div>
{{ data }}
</div>
<div>
{% endblock %}
解决方案
在烧瓶中request.form["input_name"]用于获取输入数据,但不适用于type=files
可通过request.files["input_name"]访问的输入,始终enctype=multipart/form-data
在表单中使用。您可以在官方文档中获得更多信息:
https ://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/
另一方面,request.files['filename']是 FileStorage 类型,该函数open(f)
需要str、bytes 或 os.PathLike 对象,而不是 FileStorage。
以下代码应该可以工作:
from flask import render_template, request, redirect
from app import app
import os
import csv
@app.route('/', methods=["GET", "POST"])
def index():
data = []
if request.method == 'POST':
if request.files:
uploaded_file = request.files['filename'] # This line uses the same variable and worked fine
filepath = os.path.join(app.config['FILE_UPLOADS'], uploaded_file.filename)
uploaded_file.save(filepath)
with open(filepath) as file:
csv_file = csv.reader(file)
for row in csv_file:
data.append(row)
return redirect(request.url)
return render_template('index.html', data=data)
@app.route('/help')
def help():
return render_template('help.html')
app.config['FILE_UPLOADS'] = "C:\\Users\\Zachary\\Documents\\VSCode_Projects\\monday_webapp\\app\\static\\file\\uploads"
推荐阅读
- android - import org.apache.commons.text not working
- javascript - 返回 zip 文件的 API - 将标头发送到客户端后无法设置标头?
- google-apps-script - How do you create a google script in google sheets that will create hyperlinks to video files in google drive
- google-cloud-dataflow - How to fix "...problem refreshing your credentials" error when the dataflow API and service accounts enabled and present
- c - 从 'void*' 到 'char*' 的错误无效转换
- uwp - 为数据模板 x:DataType="local:Data" 设置数据类型时出错
- html - 如何用 Bootstrap 方式实现悬停垂直导航子菜单?
- html - iframe 未完全显示可折叠菜单。将高度设置为 px,但是当菜单中的多个选项卡展开时会导致问题
- r - 字符向量列表中不匹配字符串的索引
- c# - 如何在 Xaml 文本框中显示没有空格的文本