How can I use an uploaded CSV file in my flask app

2020-07-27 04:56发布

问题:

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))

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?

Here is my full code!

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>

I'm new to flask web development.

回答1:

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)


标签: python flask