如何将.csv文件中的列存储到列表中?

时间:2014-07-01 13:31:33

标签: python csv

我有这段代码,可以通过.csv

获取DictReader文件中的所有数据
csv_path = "C:/Users/mydata.csv"

csv_database = open(csv_path, delimiters=";")    

dataDict = csv.DictReader(csv_database, delimiter=";")

我的数据库就像:

"Number0"; "date0"; "id0";...
"Number1"; "date1"; "id1";...
"Number2"; "date2"; "id2";...
...

我希望将所有列放在单独的列表中,以便它们看起来像:

[Number0, Number1, Number2,...]
[date0, date1, date2,...]
[id0, id1, id2,...]

有没有办法做到这一点,也许使用dataDict.fieldnames可以获得的标题?

感谢您的帮助

3 个答案:

答案 0 :(得分:2)

好吧,我找到了一个解决方案,所以这里是:

csv_path = "C:/Users/mydata.csv"
csv_database = open(csv_path, delimiters=";")    
data_dict = csv.DictReader(csv_database, delimiter=";")

current_row = 0

number_list = []

for row in data_dict:

    current_row += 1 # Skip heading row

    if current_row == 1:
        continue

    number_list.append(row["Number"]) # Assuming the header of your column is "Number"

# Show results

for number in number_list:
    print number 

答案 1 :(得分:1)

看看numpy你可以用它来做这样的事情:

>>> import numpy as np
>>> a = np.array([['hi','hey'],['sfg','asf']])
>>> a.transpose()
array([['hi', 'sfg'],
       ['hey', 'asf']],
      dtype='|S3')
>>> print a.transpose()[1]
['hey' 'asf']

答案 2 :(得分:0)

zip(*[line.strip().split(',') for line in open(csv_path).readlines()])