如何在Flask应用程序中使用上载的CSV文件? [英] How can I use an uploaded CSV file in my flask app?

查看:51
本文介绍了如何在Flask应用程序中使用上载的CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created an upload system with the official flask tutorial. Now I want to use the uploaded file in my web app to read as pandas data frame then use it for another purpose. I used the following line

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

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

to do that. But It didn't work for me, how can I read the uploaded file from the storage and assign it to pandas data frame?

这是我的完整代码!

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开发的新手.

推荐答案

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

The issue looks like you're just not reading the file from where you saved it. Try this:

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)

这篇关于如何在Flask应用程序中使用上载的CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆