Skip to main content

How to compare two files in Python

How to compare two files in Python.

Here's a detailed step-by-step tutorial on how to compare two files in Python.

Step 1: Import the necessary modules First, you need to import the filecmp module, which provides functions to compare files and directories.

import filecmp

Step 2: Specify the file paths Next, you need to specify the paths of the two files you want to compare. You can either provide absolute paths or relative paths based on your current working directory.

file1 = 'path/to/file1.txt'
file2 = 'path/to/file2.txt'

Step 3: Compare the files To compare the two files, you can use the filecmp.cmp() function. This function returns True if the contents of the files are identical, and False otherwise.

result = filecmp.cmp(file1, file2)

Step 4: Display the comparison result Finally, you can print the result of the file comparison to the console.

if result:
print("The files are identical.")
else:
print("The files are different.")

Complete code example:

import filecmp

file1 = 'path/to/file1.txt'
file2 = 'path/to/file2.txt'

result = filecmp.cmp(file1, file2)

if result:
print("The files are identical.")
else:
print("The files are different.")

That's it! You have successfully compared two files in Python.