如何在flask应用程序中使用上载的csv文件?

时间:2018-07-08 14:29:54

标签: python flask

我使用官方烧瓶指南创建了一个上传系统。现在,我想在Web应用程序中使用上载的文件读取为熊猫数据框,然后将其用于其他目的。 我使用了以下行

df = pd.read_csv(url_for('static', filename=filename))

做到这一点。但这对我不起作用,如何从存储中读取上传的文件并将其分配给pandas数据框?

这是我的完整代码!

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.',1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET','POST'])
def upload_file(filename=None,column=None, data=None):
    if request.method == 'POST':
        if 'file' not in request.files:
            flash("No file part")
            return redirect(request.url)

        file = request.files['file']

        if file.filename == '':
            flash("No selected file")
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))


            df = pd.read_csv(url_for('static', filename=filename))
            column = list(df)
            data = [list(df[d]) for d in column]

    return render_template('index.html', filename=filename, data=data, column=column)

index.html

<!doctype <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Upload File</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <script src="main.js"></script>
</head>
<body>
    {% if data %}
    <p>Data Found!!!</p>
    {% endif %}
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
</body>
</html>

我是Flask Web开发的新手。

1 个答案:

答案 0 :(得分:1)

问题似乎是您没有从保存文件的位置读取文件。试试这个:

filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
df = pd.read_csv(file_path)