How do i make a sublist of every CSV row and put that sublist inside a list

被刻印的时光 ゝ 提交于 2021-02-11 12:22:28

问题


I'm making a sublist of every row inside a csv file but i'm getting a single list back

wines_list = []

for row in wines:
    wines_list.append(row)

print(wines_list)

This returns:

['id', 'country', 'description', 'designation', 'points', 'price', 
'province', 'taster_name', 'title', 'variety', 'winery', 'fixed acidity', 
'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free 
sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 
'alcohol']

But i wan't it to append all values to sublist, and append that to wines_list

So i want wines_list to become something like:

[[1, 'netherlands', 'description of the wine', 'designation', 'points', 'price', 
'province', 'taster_name', 'title', 'variety', 'winery', 'fixed acidity', 
'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free 
sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 
'alcohol'], ANOTHER SUB LIST HERE]

回答1:


easiest way is something like this

import csv
pathtocsv='path/to/file'
with open(pathtocsv,'r') as cfile:
    creader=csv.reader(cfile,delimiter=',')
    wines_list=list(creader)

print(wines_list)

then wines_list will be a list of lists



来源:https://stackoverflow.com/questions/55477180/how-do-i-make-a-sublist-of-every-csv-row-and-put-that-sublist-inside-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!