如何制作每个CSV行的子列表并将该子列表放在列表中 [英] How do i make a sublist of every CSV row and put that sublist inside a list

查看:42
本文介绍了如何制作每个CSV行的子列表并将该子列表放在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个csv文件中的每一行创建一个子列表,但是我又得到了一个列表

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)

这将返回:

['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']

但是我不希望将所有值附加到子列表,并将其附加到wines_list

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

所以我希望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]

推荐答案

最简单的方法是这样的

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

print(wines_list)

然后 wines_list 将是列表列表

这篇关于如何制作每个CSV行的子列表并将该子列表放在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆