如何在Python中将CSV列导入为列表?

时间:2018-02-08 18:19:17

标签: python list csv

我在第一列中有一个带有词汇单词的大型CSV,在第二列中有定义。我想在我的iPython工作区中访问这些CSV列中的值,我将把每个CSV列的内容放入一个列表中。

让我们说我的示例CSV如下所示:

study_list.csv = [
vocabulary,translation
machen,make
gehen,go
geben,give]

我试图在iPython中结束这样的事情:

vocabulary = ["machen", "gehen", "geben"]
translation = ["make", "go", "give"]

一旦这些列表在Python中定义,我应该能够这样做:

print(vocabulary)
>machen, gehen, geben

print(translation)
>make, go, give

3 个答案:

答案 0 :(得分:1)

with open('study_list.csv','r') as csv_file:
    lines = csv_file.readlines()

vocabulary = []
translation = []
for line in lines
    data = line.split(',')
    vocabulary.append(data[0])
    translation.append(data[1])

您可以为for循环上方的其他列创建其他列表,并使用相应的索引将其附加到其中。

答案 1 :(得分:1)

Matt_G的回答非常适合您的确切问题(例如,一个小而简单的CSV),但如果您每个人都有更大的CSV或未知数量的列,或者只是想自动创建列表,我建议使用字典列表下面的代码将采用任何形状的CSV文件并将其导入列表字典,所有CSV标题(从文件的第0行)作为字典键。例如,从您的示例CSV:outputDict['vocabulary']==["machen", "gehen", "geben"]。文件中的标题可以作为带有outputDict.keys()

的字典键返回
with open('study_list.csv','r') as f:
    lines = f.readlines()

headers=lines[0].rstrip().split(',')    # rstrip removes end-of-line chars
numLines = len(lines)

linelist = [x.rstrip().split(',') for x in lines[1:numLines+1]]       # create lineList to include only numLines elements
outputDict = {keyVal:[x[idx] for x in linelist if len(x)==len(headers)] for idx,keyVal in enumerate(headers)}    # list comprehension within dictionary comprehension to split each element by its header and create dictionary of lists 

答案 2 :(得分:0)

import csv
vocabulary = []
translation = []
with open('study_list.cs', mode='r') as f:
    reader = csv.reader(f, delimiter=',')  
    for n, row in enumerate(reader):
        if not n:#skip header
            continue
        vocabulary.append(row[0]) 
        translation.append(row[1]) 

或者您可以使用

import csv
vocabulary = []
translation = []
with open('study_list.cs', mode='r') as f:
     reader = csv.DictReader(f, delimiter=',')  
     for n, row in enumerate(reader):
         if not n:#skip header
             continue
         vocabulary.append(row['vocabulary']) 
         translation.append(row['translation'])