如何将文本文件的每一列打开为单独的列表?
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
答案 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)