Home > Enterprise >  how to compare difference in 2 txt files and output to a new txt file and print to shell using pytho
how to compare difference in 2 txt files and output to a new txt file and print to shell using pytho

Time:10-23

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

working files in this link

expected output in txt file

CodePudding user response:

of course use diff

difflib.Differ

CodePudding user response:

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
  • Related