Python program to compare two text files

In this article, we will learn how to compare two text files in Python. We will try to implement this problem by using various methods.

Files used in examples

Method 1: Using filecmp.cmp()

Python provides a module called filecmp that helps compare files. The filecmp.cmp() returns a three list containing matched files, errors, mismatched files. filecmp.cmp() has can operate in two modes

  • Shallow mode: In this mode, only metadata of files are compared like size, date modified, etc…
  • deep mode: In this mode content of the files is compared.
import filecmp
import os

file1 = "C:\\Users\\Abinash\\Desktop\\Python Programs\\input1.txt"
file2 = "C:\\Users\\Abinash\\Desktop\\Python Programs\\input2.txt"

# shallow mode, compare metadata
result = filecmp.cmp(file1, file2)
print(result)

#deep mode, Compare content
result = filecmp.cmp(file1, file2, shallow=False)
print(result)

Output

False
False

Method 2: Comparing both files line by line

1. Open the files using the open() method.

2. Loop through both files and compare them line by line.

3. If both lines are the same then print SAME.

4. Else print both lines.

file1 = open("C:\\Users\\Abinash\\Desktop\\Python Programs\\input1.txt", "r")
file2 = open("C:\\Users\\Abinash\\Desktop\\Python Programs\\input2.txt", "r")

i = 0

for l1 in file1:
    i += 1
    for l2 in file2:
        if l1 == l2:
            print("Line ", i,": ")
            print("Both the lines are same")
        else:
            print("Line ", i,": ")
            print("File 1: ", l1)
            print("File 2: ", l2)
        break

file1.close()
file2.close()

Output

Line 1 : 
File 1: During the first part of your life, you only become aware of happiness once you have lost it.
File 2: ‘Margareta! I’m surprised at you! We both know there’s no such thing as love!’

Line 2 :
Both the lines are same

Line 3 :
File 1: that you are, at the end of the day, going to lose it.
File 2: Tatyana snuffed our her cigarette. That sly smile. ‘Mutations of wanting.’

Line 4 :
Both the lines are same

Line 5 : 
File 1: I also understood that I hadn’t reached the third age, in which anticipation of the loss of happiness prevents you from living.
File 2: When a man blows his nose you don’t call it love.

Also, read

Leave a Reply

Your email address will not be published.