S
S
Sheryorg2015-02-05 22:01:39
Python
Sheryorg, 2015-02-05 22:01:39

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

Second 2.csv:
template1;OLD;1000
template2;NEW;1030
template5;OLD;1020
template6;OLD;1010

I try with this script
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)

do a merge of two files, outputs
template1;OLD;1000
template2;NEW;1000

if I add one more condition
elif tom1 != fin1 and tom2 != fin2:
            b.append(fin1 + ';' + fin2 + ';1000\n')
            break

get
template1;OLD;1000

template2;NEW;1000

template2;NEW;1000

template2;NEW;1000

Can you please tell me how to process these two files so that all records missing in the first file end up in the second?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
Oscar Django, 2015-02-05
@Sheryorg

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]))

Job in progress

S
Sheryorg, 2015-02-05
@Sheryorg

Should work

template1;NEW;1000
template2;OLD;1010
template3;OLD;1020
template4;OLD;1000
template5;OLD;1020
template6;OLD;1010

those. everything that was missing in the first file should be added from the second.

Y
yuliymo, 2015-02-05
@yuliymo

for line in open("file2"):
    if line not in open("file1"):
        open("file1","a").write(line)

V
Vladimir Abramov, 2015-02-05
@kivsiak

And there are also wonderful batteries
https://docs.python.org/2/library/difflib.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question