Chris Breen
Chris Breen

Reputation: 1

Comparing two lists of strings .CSV

I'm trying to write a script to compare two lists of strings from different spreadsheets and to print off a list of strings common to both spreadsheets. I'm a total novice, but so far I've got:

import csv
f1 = file("KaySinTan09.csv", "r")
f2 = file("Khanna11.csv", "r")

c1=csv.reader(open('KaySinTan09.csv', 'rb'), delimiter=' ', quotechar='|')
c2=csv.reader(open('Khanna11.csv', 'rb'), delimiter=' ', quotechar='|')

output = c1.intersection(c2)
print output

I get an error saying "AttributeError: '_csv.reader' object has no attribute 'intersection'".

Any advice on where I'm going wrong?

Upvotes: 0

Views: 638

Answers (2)

Andrew Sledge
Andrew Sledge

Reputation: 10351

csv.reader does not return a list - it returns a CSV reader object - so the .intersection method will not work. Maybe this will:

c1=csv.reader(open('KaySinTan09.csv', 'rb'), delimiter=' ', quotechar='|')
c2=csv.reader(open('Khanna11.csv', 'rb'), delimiter=' ', quotechar='|')

c1_list = []
c2_list = []

for c in c1:
  c1_list.append(c)
for c in c2:
  c2_list.append(c)

output = set(c1_list).intersection(set(c2_list))
print output

This is not tested.

Upvotes: 0

Miki Tebeka
Miki Tebeka

Reputation: 13850

csv.reader is not a set, you need to convert it to one in order to do this:

c1= set(csv.reader(open('KaySinTan09.csv', 'rb'), delimiter=' ', quotechar='|'))
c2 = set(csv.reader(open('Khanna11.csv', 'rb'), delimiter=' ', quotechar='|'))

output = c1.intersection(c2)
print output

Upvotes: 2

Related Questions