如何打开文本文件的每一列作为单独的列表?

时间:2013-11-08 12:18:38

标签: python list csv

如何将文本文件的每一列打开为单独的列表?

import csv    
infile = open ('data.txt', 'r')
reader = csv.reader(infile, delimiter=' ')
col1 = [line[0] for line in reader]
print (col1)
col2 = [line[1] for line in reader]
print (col2)
But column2 is empty. Any idea???

data.txt看起来如下:

a d 1
b e 2
c f 3

2 个答案:

答案 0 :(得分:5)

在代码中col2为空,因为在第一次迭代(col1的列表理解)之后,迭代器已经用完了。

您可zip使用*

import csv
with open('abc.csv') as f:
    reader = csv.reader(f, delimiter=' ')
    c1, c2, c3 = zip(*reader)
    print c1
    print c2
    print c3

<强>输出:

('a', 'b', 'c')
('d', 'e', 'f')
('1', '2', '3')

答案 1 :(得分:0)

with open ('data.txt','r') as infile:
    col1= [i.strip().split(' ')[0] for i in infile]
with open ('data.txt','r') as infile:    
    col2= [i.strip().split(' ')[1] for i in infile]
    print (col1)
    print (col2)