Python filecmp method

Module filecmp is used to compare file directories in shallow or deep mode. Filecmp is part of the python utility module.

filecmp.cmp method is used to compare two file,method by default performs the shallow
Comparison by default is set True, meaning that the file signature size,data modification.both file are compared if their identical signatures are equal consider as same file.

Syntax
filecmp.cmp(file1,file2,shallow=True)

file1: this is file which we have to compare

file2 : this is a file two ,which we have to compare too

Shallow : this is optional it is return the bool value either it will true or false

import filecmp 
  
  

file1 = "C:/Users/ASUS/Desktop/abc.txt"
  

file2 = "C:/Users/ASUS/Desktop/test.txt"
comp = filecmp.cmp(file1, file2) 
print(comp)  
comp = filecmp.cmp(file1, file2, shallow = False) 
print(comp)

Output

C:\Users\ASUS\Desktop>python test.py
False
False

Comparison when Shallow is True

import filecmp
# from filecmp import cmpfiles

dir1 = "C:/Users/ASUS/Desktop/dir1/"
dir2 = "C:/Users/ASUS/Desktop/dir2/"
common = ["abc.txt", "test.txt"]

# shallow comparison
match, mismatch, errors = filecmp.cmpfiles(dir1, dir2, common)

# Shallow = True
print("Shallow Comparison")
print("Match: ", match)
print("Mismatch: ", mismatch)
print("Errors: ", errors)

Output

C:\Users\ASUS\Desktop>python cmp.py
Shallow Comparison
Match:  []
Mismatch:  []
Errors:  ['abc.txt', 'test.txt', 'test2.txt']

Deep Comparison

import filecmp
# from filecmp import cmpfiles

dir1 = "C:\\Users\\ASUS\\Desktop\\dir1\\"
dir2 = "C:\\Users\\ASUS\\Desktop\\dir2\\"
common = ["abc.txt	", "test.txt","test2.txt"]

# shallow comparison
match, mismatch, errors = filecmp.cmpfiles(dir1, dir2, common,shallow=False)

# Shallow = False
print("Deep Comparison")
print("Match: ", match)	
print("Mismatch: ", mismatch)
print("Errors: ", errors, "\n\n")

Output

C:\Users\ASUS\Desktop>python cmp.py
Deep Comparison
Match:  []
Mismatch:  []
Errors:  ['abc.txt', 'test.txt', 'test2.txt']
Subscribe Now