【问题标题】:How make a list with a csv file using flask?如何使用烧瓶制作带有 csv 文件的列表?
【发布时间】:2020-07-19 01:53:23
【问题描述】:

我正在用 Flask 做一个项目,重点是: 在一条路线中,我生成一个 .csv 文件来下载它,其中包含来自 MySQL 的信息,如下所示 文件.csv

1,17.0,46.0,2.80696,0.559892,0.534016,0.543017,24.25,22:30:00,2020-04-28
2,17.0,47.0,2.80884,0.559142,0.534016,0.537016,24.5,23:00:00,2020-04-28
3,16.0,53.0,2.80921,0.547517,0.534016,0.537016,24.5,23:30:00,2020-04-28
4,16.0,49.0,2.80959,0.548079,0.534016,0.537016,24.25,00:00:00,2020-04-29

另一方面,我的服务器的其他路由可以选择上传文件,但上传文件时我可以看到纯文本: This is the output when upload my file

这个想法是从这个纯文本创建一个具有以下结构的列表:

dato[
   [1,17.0,46.0,2.80696,0.559892,0.534016,0.543017,24.25,22:30:00,2020-04-28],
   [2,17.0,47.0,2.80884,0.559142,0.534016,0.537016,24.5,23:00:00,2020-04-28],
   [3,16.0,53.0,2.80921,0.547517,0.534016,0.537016,24.5,23:30:00,2020-04-28],
   [4,16.0,49.0,2.80959,0.548079,0.534016,0.537016,24.25,00:00:00,2020-04-29]
]

我尝试了很多东西,但我做不到。 这是我的 app.py

@app.route('/upload',methods = ['POST'])
def upload_route_summary():
    if request.method == 'POST':
        # Create variable for uploaded file
        f = request.files['fileupload']  

        #store the file contents as a string
        fstring = f.read()
        
        #create list of dictionaries keyed by header row
        #csv_dicts = [{k: v for k, v in row.items()} for row in csv.DictReader(fstring.splitlines(), skipinitialspace=True)]

        #do something list of dictionaries
    return fstring

【问题讨论】:

    标签: python csv flask


    【解决方案1】:

    我假设您的意思是您想要一个列表列表,因为您的示例输出如下所示:

    dato[
       [1,17.0,46.0,2.80696,0.559892,0.534016,0.543017,24.25,22:30:00,2020-04-28],
       [2,17.0,47.0,2.80884,0.559142,0.534016,0.537016,24.5,23:00:00,2020-04-28],
       [3,16.0,53.0,2.80921,0.547517,0.534016,0.537016,24.5,23:30:00,2020-04-28],
       [4,16.0,49.0,2.80959,0.548079,0.534016,0.537016,24.25,00:00:00,2020-04-29]
    ]
    

    csv.DictReader 需要标题行,除非您提供 fieldnames (doc) (another SO question):If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames

    提供字段名称,遍历每一行以访问元组将为您提供列表列表:

    data = []
    for row in csv.DictReader(fstring.splitlines(), fieldnames=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']):
      data.append([item[1] for item in row.items()])
    

    或者,DictReader 文档指出:If a row has more fields than fieldnames, the remaining data is put in a list and stored with the fieldname specified by restkey (which defaults to None)

    因此您可以为fieldnames 传入任何空列表并访问None 中的整个列表:

    data = []
    for row in csv.DictReader(fstring.splitlines(), fieldnames=[]):
        data.append(row[None])
    

    【讨论】:

    • 谢谢,但是当运行你的代码时我遇到了这个问题 _csv.Error: iterator should return strings, not bytes (你是在文本模式下打开文件吗?)
    猜你喜欢
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 2019-06-24
    相关资源
    最近更新 更多