-2

I am trying to write a program that will open files, read the contents and compare them to other files opened. I need to show if they are Not close enough alike, Similar, or exact copies of each other. I am trying to use the filecmp module, but it's not working for me. Here's what I have so far:

import filecmp

#Opens selected files
file1 = open('file1.txt')
file2 = open('file2.txt')

#Compares different files
filecmp.cmp('file1','file2', shallow=False)

#Closes Files
filecmp.clear_cache()
close.file1
close.file2

Any suggestions?

John
  • 1
  • 1

2 Answers2

3

filecmp is the wrong tool to use
Try this instead:
1. Load the contents of each file into a list
2. Turn the lists into sets 3. Subtract one set from the other 4. The result provides the differences between the two which you can analyse.

For example:

list1 = set(line.strip() for line in open("file1.txt"))
list2 = set(line.strip() for line in open("file2.txt"))
diff1 = list1 - list2 # subtract 1 set from the other for the difference
diff2 = list2 - list1 # subtract 1 set from the other for the difference
save = open("diff.txt",'w') # Write file differences details for analysis
for i in diff1:
    save.write(i+'\n')
save.close()
save = open("diff2.txt",'w') # Write file differences details for analysis
for i in diff2:
    save.write(i+'\n')
save.close()

or look at difflib https://docs.python.org/3.5/library/difflib.html#difflib.Differ

Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60
0
>>> import filecmp
>>> filecmp.cmp('C://Desktop/a.txt', 'C://Desktop/b.txt')
True
>>> 

In this case I have 2 text files a.txt and b.txt. Both files contain the same one line of string.

If I change the string in one of the files to something different, the output is False

Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48