Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython: filecmp.cmp() method

Python: filecmp.cmp() method

Filecmp module in Python provides functions to compare files and directories. This module comes under Python’s standard utility modules. This module also consider the properties of files and directories for comparison in addition to data in them. filecmp.cmp() method in Python is used to compare two files. This method by default performs shallow comparison (as by default shallow = True) that means only the os.stat() signatures (like size, date modified etc.) of both files are compared and if they have identical signatures then files are considered to be equal irrespective of contents of the files. If shallow is set to False then the comparison is done by comparing the contents of both files.

Note:
The cmp function in Python 2 is used to compare two objects and return a value indicating their relative order.
In Python 3, the cmp function was removed and the __lt__, __le__, __gt__, and __ge__ methods were added to implement comparison operations.

Instead of using cmp, you should use the appropriate comparison operator (e.g., <, <=, >, >=) or the __lt__, __le__, __gt__, and __ge__ methods.

The cmp function is still available in Python 2, but it has been deprecated and is not recommended for use in new code. 
It is recommended to use the comparison operators or methods mentioned above instead.

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

Parameter: 
file1: The path of first file to be compared. It can be a string, bytes, os.PathLike object or an integer representing the path of the file.
file2: The path of second file to be compared. It can be a string, bytes, os.PathLike object or an integer representing the path of the file.
shallow (optional): A bool value ‘True’ or ‘False’. The default value of this parameter is True. If its value is True then only the metadata of files are compared. If False then the contents of the files are compared. 

Return Type: This method returns a bool value True if specified files are equal or False if they are not.

Code: Use of filecmp.cmp() method to compare two files 

Python3




# Python program to demonstrate
# filecmp.cmp() method
   
 
import filecmp
 
 
# Path of first file
file1 = "/home/Lazyroar/Desktop/gfg/data.txt"
 
# Path of second file
file2 = "/home/Lazyroar/Desktop/gfg/gfg.txt"
  
# Compare the os.stat()
# signature i.e the metadata
# of both files
comp = filecmp.cmp(file1, file2)
 
# Print the result of comparison
print(comp)
 
# Compare the
# contents of both files
comp = filecmp.cmp(file1, file2, shallow = False)
 
# Print the result of comparison
print(comp)


Output:

False
True
RELATED ARTICLES

Most Popular

Recent Comments