Answer the question
In order to leave comments, you need to log in
How to compare two files in Python and add missing elements?
Good day.
There are two files. First 1.csv:
template1;NEW;1000
template2;OLD;1010
template3;OLD;1020
template4;OLD;1000
template1;OLD;1000
template2;NEW;1030
template5;OLD;1020
template6;OLD;1010
b = []
for tom in open('1.csv', 'r'):
tom1, tom2, tom3 = tom.split(';')
for fin in open('2.csv', 'r'):
fin1, fin2, fin3 = fin.split(';')
if tom1 == fin1 and tom2 == fin2:
b.append(tom1 + ';' + tom2 + ';' + str(int(tom3) + 1) + '\n')
break
elif tom1 == fin1 and tom2 != fin2:
b.append(tom1 + ';' + fin2 + ';1000\n')
break
for i in b:
print(i)
template1;OLD;1000
template2;NEW;1000
elif tom1 != fin1 and tom2 != fin2:
b.append(fin1 + ';' + fin2 + ';1000\n')
break
template1;OLD;1000
template2;NEW;1000
template2;NEW;1000
template2;NEW;1000
Answer the question
In order to leave comments, you need to log in
I will add. UPDATE: so short
result = {}
for tom in open('k1.csv', 'r'):
t1, t2, t3 = tom.replace('\n', '').split(';')
result[t1] = (t2, t3)
for tom in open('k2.csv', 'r'):
t1, t2, t3 = tom.replace('\n', '').split(';')
if t1 not in result.keys():
result[t1] = (t2, t3)
for k in result.keys():
print('{}: {}'.format(k, result[k]))
Should work
template1;NEW;1000
template2;OLD;1010
template3;OLD;1020
template4;OLD;1000
template5;OLD;1020
template6;OLD;1010
for line in open("file2"):
if line not in open("file1"):
open("file1","a").write(line)
And there are also wonderful batteries
https://docs.python.org/2/library/difflib.html
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question