如何使用flask使用csv文件制作列表?

2024-09-28 17:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Flask做一个项目,重点是: 在一个路径中,我生成一个.csv文件,从MySQL下载信息,如下所示 file.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

Tags: 文件ofcsvthe文本appforrequest
1条回答
网友
1楼 · 发布于 2024-09-28 17:31:25

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

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需要一个头行,除非您提供了fieldnamesdoc)(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])

相关问题 更多 >