简体   繁体   中英

Uploading file on flask and cleaning file up

I am trying to use flask to build a web app that will allow users to upload a file, it will run a script that cleans up the csv file and returns the cleaned up version.

I have written this code out, however, I get this error message when I try and run the web app:

builtins.FileNotFoundError
FileNotFoundError: [Errno 2] No such file or directory: 'Entrepreneur_list_-_Sheet1.csv'

Here is the code I have written for this function:

import os
from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = './Downloads/gmbreports'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

ALLOWED_EXTENSIONS = 'csv'

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    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('You need to upload a csv 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))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Google My Business Discovery Report Builder</title>
    <h1>Upload GMB Discovery csv</h1>
    <form method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''
from flask import send_from_directory


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    #once you upload the file you get cleaned up visualisations
    file_one = open(filename)
    file_two = open(filename,'w')
    #cleaning up csv
    for row in file_one:
        row = row.strip()
        row = row[1:-1]
        row = row.replace('""','"')
        file_two.write(row+'\n')
    file_two.close()
    file_one.close()
    discovery= pd.read_csv(filename)
    discovery_clean= discovery.iloc[1:] # remove top row
    cols = list(discovery_clean.columns[4:])
    discovery_clean[cols] = discovery_clean[cols].apply(pd.to_numeric,errors='coerce')
    #create visualisation

    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)
if __name__=='__main__':
    app.run(debug=True)

Have you tried replacing the filename variable in the uploaded_file route with the actual path to the uploaded csv file? As shown below:

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    path = UPLOAD_FOLDER + "/" + filename
    #once you upload the file you get cleaned up visualisations
    file_one = open(path)
    file_two = open(path,'w')
    #cleaning up csv
    for row in file_one:
        row = row.strip()
        row = row[1:-1]
        row = row.replace('""','"')
        file_two.write(row+'\n')
    file_two.close()
    file_one.close()
    discovery= pd.read_csv(path)
    discovery_clean= discovery.iloc[1:] # remove top row
    cols = list(discovery_clean.columns[4:])
    discovery_clean[cols] =covery_clean[cols].apply(pd.to_numeric,errors='coerce')
    #create visualisation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM