Python csv comparison using reader -
i tried script compare 2 csv files..
import csv file1 = open("1.csv", "r") reader1=csv.reader(file1) reader1.next() file2 = open("2.csv", "r") reader2=csv.reader(file2) reader2.next() file3 = open("file3.txt", "w") file4 = open("file4.txt", "w") file1.seek(0,0) file2.seek(0,0) list1 = file1.readlines() list2 = file2.readlines() in list1: j in list2: if == j: file3.write(i) file3.write(j) else : file4.write(i) file4.write(j) continue
in output getting headers included , plus mismatched files repeating. eg:if 1.csv contains
name salary 20000 b 15000 c 10000
2.csv contains
name salary 40000 d 10000 b 15000 c 9000
output should be
file3: b 15000 b 15000 file4: 20000 40000 c 10000 c 9000 ------(no d in 1.csv) d 10000
try 1 . works . showed u mechanism search . u can modify make efficient
import csv file1 = open("book1.csv", "r") reader1=csv.reader(file1) print reader1 reader1.next() file2 = open("book2.csv", "r") reader2=csv.reader(file2) reader2.next() file3 = open("file3.txt", "w") file4 = open("file4.txt", "w") file1.seek(0,0) file2.seek(0,0) list1 = file1.readlines() print list1 list2 = file2.readlines() print list2 d={} j in list2: temp=j.split(',') print temp d[temp[0]]=temp[1] print d i,j in zip(list1,list2): key = i.split(',') try: if d[key[0]]: print d[key[0]] if d[key[0]]==key[1]: file3.write(i) file3.write(j) else: file4.write(i) file4.write(j) except: print key[0],'not in file 2' continue
Comments
Post a Comment