在烧瓶上上传文件并清理文件

时间:2019-04-26 18:25:43

标签: python flask

我正在尝试使用flask建立一个允许用户上传文件的Web应用程序,它将运行一个脚本来清理csv文件并返回清理后的版本。

我已经写出了这段代码,但是,当我尝试运行Web应用程序时收到以下错误消息:

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

这是我为此功能编写的代码:

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)

1 个答案:

答案 0 :(得分:0)

您是否尝试过用上载的csv文件的实际路径替换上载的文件路径中的文件名变量?如下图所示:

Single