CPDS
CPDS

Reputation: 597

Compare each element in CSV with other using python

I want to compare each element in a csv file with all other elements using python. I have made 2 columns which are exacly same thinking I can iterate over each row.col pair. File looks like this

NAME NAME_COMPARE AAA AAA BBB BBB

The output I would like to see is: AAA,AAA AAA,BBB BBB,AAA BBB,BBB

here is the code I am using

fname = 'UA_TEST.csv'
fp = open(fname)
fp.next()
cscrd = (csv.reader(fp, delimiter='\t', doublequote=True))
for row in cscrd:
    a = row[1]
    for row in cscrd:
        b = row[2]
    print a,b

Code gives following output

AAA,AAA AAA,BBB

and then it exits it never goes through the second loop.

Any pointers?

Upvotes: 2

Views: 397

Answers (1)

Nitin
Nitin

Reputation: 2874

I think you need something like this,

import csv

fname = 'UA_TEST.csv'
fp = open(fname)
fp.next()
cscrd = (csv.reader(fp, delimiter='\t', doublequote=True))
i = 0
for row in cscrd:
    a = row[i]
    for col in row:
        b = col
        print a,b
    i += 1

This gives the output:

AAA AAA
AAA BBB
BBB AAA
BBB BBB

Upvotes: 1

Related Questions