2

How to open each column of a text file as separate list?

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???

The data.txt look as follows:

a d 1
b e 2
c f 3
4

2 回答 2

5

In your code col2 is empty because after the first iteration(List comprehension for col1) the iterator is already exhausted.

You can zip with *:

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

Output:

('a', 'b', 'c')
('d', 'e', 'f')
('1', '2', '3')
于 2013-11-08T12:21:49.260 回答
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)
于 2013-11-12T14:12:16.727 回答