2
votes

I have a text file with more than 10 lines and 3 columns like:

Classification Type  A  B
Commercial Homes     12 15
Residential Homes    10 14
................     .. ..

I want to read each column separately like:

Classification = ['Commercial Homes', 'Residential Homes'.......]
A = [12,10,....]
B = [15,14,....]

I can use split() and read them into separate lists but classification names have more than one word and I have to capture full name in the list instead of first word. Any suggestions would be appreciative.

3
What are the columns delimited with? Tabs, spaces, commas? - Cory Kramer

3 Answers

4
votes

Just use zip() to transpose the matrix represented by the csv reader object:

import csv

with open(fn) as f:
    reader=csv.reader(f, delimiter='\t')
    a, b, c = zip(*reader)

    print a
    ('Classification Type', 'Commercial Homes', 'Residential Homes')
    print b
    ('A', '12', '10')
    print c
    ('B', '15', '14')
    # trim the tuples as you wish, such as b=list(b[1:])...

Then, you may want a dict with the first value of that tuple:

data={}
for t in zip(*reader):
    data[t[0]]=t[1:]

print data    
# {'A': ('12', '10'), 'B': ('15', '14'), 'Classification Type': ('Commercial Homes', 'Residential Homes')}

Which then can be reduced to a single statement:

data={t[0]:t[1:] for t in zip(*reader)}
# {'A': ('12', '10'), 'B': ('15', '14'), 'Classification Type': ('Commercial Homes', 'Residential Homes')}
0
votes

Something like this might work:

#!/usr/bin/python
with open('./mydata', 'r') as raw_data:
    data = [line.strip().split() for line in raw_data.readlines()]
header = data.pop(0) ## Pop off header, removed from list
a = [record[1] for record in data]
b = [record[2] for record in data]

Obviously we are traversing the list twice, once for a and again for b. For small data sets this won't pose any performance issue.

Alternatively we could do something like this:

#!/usr/bin/python
a = list()
b = list()
with open('./mydata', 'r') as raw_data:
    for line in raw_data:
        if line.startswith('Classification'):
            continue # skip the header line
        line = line.strip().split()
        a.append(line[1])
        b.append(line[2])

This is a bit more verbose. But it does the work in a single pass through the data.

0
votes

Use csv library to do the task

import csv

def main():
    with open(r'CSVReaderData.txt', 'r') as f:
        reader = csv.reader(f, delimiter='\t')
        col1, col2, col3 = zip(*reader)

    print 'Classification = ',list(col1)
    print 'A = ',list(col2)
    print 'B = ',list(col3)

if __name__ == '__main__':
    main()