无法在Flask应用中写入CSV文件

时间:2018-10-19 06:37:35

标签: python pandas csv flask

我在flask上创建了一个简单的应用程序,用户可以在其中上传包含名称的csv文件,并且它将返回一个新的csv文件,该文件将仅具有以S或M开头的名称。 当我单击上载时,它应该下载新文件,但我不知道我哪里出错了。可能是写下csv。请帮帮我。 使用Python 3.x 这是app.py

import os
import pandas as pd
import csv
from flask import Flask, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'
ALLOWED_EXTENSIONS = {'csv'}

app = Flask(__name__, static_url_path="/static")
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024


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


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        if 'file' not in request.files:
            print('No file attached in request')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            print('No file selected')
            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))
            process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), filename)
            return redirect(url_for('uploaded_file', filename=filename))
    return render_template('index.html')


def process_file(path, filename):
    update_file(path, filename)

def update_file(path, filename):
    data= pd.read_csv(path)
    work = data['first'].tolist()

    work_final=[]

    for item in work:
        if(checkitems(item) == True):
            work_final.append(item)

    headers = {}
    headers[str('content-type')] ='text/csv'
    headers['Content_Disposition'] = 'attachment; filename='+filename +'.csv'
    f = open(path + filename + '.csv' , 'wb')
    writer = csv.writer(f)
    writer.writerow(work_final)
    f.close()

def checkitems(items):
    if (items[0] == 'S' or items[0] == 'M'):
        return True
    else:
        return False


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename, as_attachment=True)


if __name__ == '__main__':
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)

这是模板index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Name Changer</title>
</head>
<body>
    <div align="center">
        <h1> Avinash Name Filter</h1>
        <h2> Upload the CSV File here</h2>
        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value=Upload>
        </form>     
    </div>
</body>
</html>

请帮帮我。

我在此处附有此示例csv

seq,first,age,date
1,Bernice,36,08/22/2013
2,Dale,63,07/18/1964
3,Oscar,53,05/02/1943
4,Elijah,57,12/13/1919
5,Chad,48,04/26/1958
6,Mabel,22,01/22/1916
7,Clayton,29,01/06/1901
8,James,47,07/01/1944
9,Olga,65,02/09/2020
10,Helena,23,03/11/2045
11,Jessie,31,01/07/2032
12,Ann,58,10/20/2058
13,Sallie,32,12/05/2009
14,Brandon,34,07/16/2067
15,Millie,61,07/10/2051
16,Travis,25,12/07/1997
17,Charlie,39,01/08/2001
18,Lester,19,01/31/1922
19,Charles,59,05/01/1929
20,Dennis,27,06/28/2050
21,Sean,28,07/12/2013
22,Jeffrey,33,10/04/2001
23,Evelyn,26,06/27/2048
24,Nell,32,03/05/1981
25,Gavin,30,04/08/2031
26,Mitchell,20,03/12/1977
27,Ruby,37,07/01/2024
28,Wesley,30,06/27/2060
29,Wesley,31,01/30/1978
30,Mina,49,10/20/2056
31,Daisy,43,04/05/1998
32,Martin,59,02/24/1964
33,Lee,39,01/24/2015
34,Timothy,58,11/20/2028
35,Rosetta,42,08/11/2020
36,Darrell,51,11/11/1984
37,Bess,42,06/04/1956
38,Estelle,52,06/08/2042
39,Aaron,65,09/03/2021
40,Jon,50,11/15/2000
41,Cory,32,06/14/1901
42,Leroy,63,07/02/2003
43,Grace,19,11/24/1929
44,Dennis,63,07/31/1927
45,Christopher,24,11/21/1968
46,Nancy,24,03/05/1948
47,Edith,65,08/31/1961
48,Raymond,39,01/10/1948
49,Agnes,22,11/28/1921
50,Steve,47,04/09/2052

这是csv的链接-https://a.uguu.se/DMHQAUYuqqFh_test.csv

1 个答案:

答案 0 :(得分:0)

我测试了您的应用程序,没有 update_file()函数,它将在上传后下载文件。因此,您在处理 .csv 文件时出错。如果您可以添加示例csv文件,那就太好了(抱歉,无法发表评论,因为我不是stackoverflow的新手。)

编辑:

我发现了错误。您应该输入:

f = open(path + filename + '.csv' , 'w')

您正在以二进制模式读取,这就是为什么无法写入带有字符串的数组的原因。 此外,csv阅读器从该文件读取的第一件事是1,2,3,4 ...而不是S或M。请检查一下,您将在新的CSV文件中进行有效的写入操作