codingn00b
codingn00b

Reputation: 31

how to compare difference in 2 txt files and output to a new txt file

How to compare difference in 2 txt files and output and print it to shell?

working files in this link

Upvotes: 0

Views: 912

Answers (2)

Corralien
Corralien

Reputation: 120499

Use drop_duplicates with Pandas:

df1 = pd.read_csv('members_1.txt', header=None).drop_duplicates()
df2 = pd.read_csv('members_2.txt', header=None).drop_duplicates()
out = pd.concat([df1, df2]).drop_duplicates(keep=False)

Output

>> print(*out[0].to_list(), sep='\n')
LEE RI KE
LIM YONG
KOH CHEE KIAT
LEE YONG
KOH CHEW KIAT
LEE RI KHEE

OR

Use set in Python:

with open('members_1.txt') as fp1, open('members_2.txt') as fp2:
    data1 = set([l.strip() for l in fp1])
    data2 = set([l.strip() for l in fp2])
    out = data1.symmetric_difference(data2)

Output:

>>> print(*out, sep='\n')
KOH CHEW KIAT
LEE RI KE
LEE YONG
KOH CHEE KIAT
LEE RI KHEE
LIM YONG

Update: export to file

with open('output.txt', 'w') as fp:
    print(*out, sep='\n', file=fp)

Upvotes: 1

dzNET
dzNET

Reputation: 970

of course use diff

difflib.Differ

Upvotes: 0

Related Questions