使用不同行的python比较2个CSV文件

时间:2018-01-17 10:26:30

标签: python python-2.7 file csv

我有两个csv文件,例如one.csv和two.csv。文件格式为One.csv:

ID1 , att 1 , att 2

for two.csv

ID2, att2, att1 

现在我想在att1和att2相同的地方打印ID1,ID 2,att1,att2。我已经编写了这段代码,但它只打印了一个这样的案例但是还有更多像这样的案例

import csv
path1 ="/home/vishver/Desktop/"
file1 =open(path1 +"one.csv","r")
file2 =open(path1 +"two.csv","r")

reader1 =csv.reader(file1)
reader2 =csv.reader(file2)
count =0
for line1 in reader1:
	for line2 in reader2:	
		if line1[1] == line2[2] or line1[2] == line2[1]:
			t=line2[0],line1[0],line1[1],line1[2]			
			print(t)
			count+=1
	
print count

1 个答案:

答案 0 :(得分:0)

如果您只想打印常用属性的总数,请尝试以下方法:

path1 ="/home/vishver/Desktop/"
file1 =open(path1 +"one.csv","r")
file2 =open(path1 +"two.csv","r")

reader1 =csv.reader(file1)
reader2 =csv.reader(file2)

count =0
file1_att1 = []
file1_att2 = []
file2_att1 = []
file2_att2 = []


for line1 in reader1:
    file1_att1.append(line[1])
    file1_att2.append(line[2])

for line1 in reader1:
    file2_att1.append(line[1])
    file2_att2.append(line[2])

common1 = (set(file1_att1).intersection(file2_att2))
common2 = (set(file1_att2).intersection(file2_att1))

print common1+common2