Noah Daniel
Noah Daniel

Reputation: 1

Python script to print only the difference between two text files

I was looking for some help to write a Python script to print only the difference and not anything extra in the output.

For example:

Contents of File1 :-

['Tom','Joe','Kim']

Contents of File2 :-

['Tom','Leo','Cho','Joe','Kim']

I need the following as output when I run the script:

['Leo','Cho']

I tried using difflib library functionalities, but it just doesn't seem to give me only the difference as output!

Upvotes: -2

Views: 61

Answers (2)

Malo
Malo

Reputation: 1313

You can use the set.union(..) and set.intersection(..) methods to obtain what you are looking for. It is included in standard, no import to make:

file1 = ['Tom','Joe','Kim']
file2 = ['Tom','Leo','Cho','Joe','Kim']

result = set(file1).union(set(file2)) - set(file1).intersection(set(file2))

print( list(redsult) )

Output is:

['Leo', 'Cho']

Upvotes: 0

Gооd_Mаn
Gооd_Mаn

Reputation: 1088

  1. You can convert your lists to sets, so you can find difference of unique items.
  2. To keep the same formatting then you convert back set to list.
file1 = ['Tom','Joe','Kim']
file2 = ['Tom','Leo','Cho','Joe','Kim']
diff = list(set(file2)-set(file1)

Output:

['Cho', 'Leo']

Note, if don't know from which list to subtract (i.e the largest one) you can use the following code. It uses "OR" operator:

diff = list(set(file2)-set(file1)|set(file1)-set(file2))

Upvotes: 1

Related Questions