File Handling and File Comparison In Python

Posted By : Aakash Vishwakarma | 31-Oct-2022

File Handling and File Comparison In Python


In Python, there are several functions as well as libraries that are available for File handling and File comparison. File handling is a crucial part of any web application. In this blog, we will learn how to Compare two files and handle different operations on the file.


File Handling: The key function for working with files in Python is the open() function. The open() function takes two parameters filename, and mode.

Mode: we have different modes like “r” for read, “w” for write, “a” for append and “X” for create.




Suppose we need to read a file then:


file = open(“file_name.extension”, “r”)




file = open(“file1.txt”, “r”)



here read is a function used to read the entire file.

Note: it’s a good practice to close your file once your work is done.




file = open(“file1.txt”, “r”)



Here close() is used to close the file object. And readline() is a function used to read a file line by line.


So now we know how we can access a file and how we will close a file now we will move to file comparison.


File Comparison:

Create a file and write the below code:


# First Open your files


file1 = open(“file1.txt”, “r”)

file2 = open(“file2.txt”, “r”)


# Write comparison algorithm


for f1, f2 in zip(file1, file2)

      if f1 == f2:

            print(“same---> file1: ”, f1, “ file2:”, f2)


            print(“Different---> file1: ”, f1, “ file2:”, f2)

# Close File





Related Tags

About Author

Author Image
Aakash Vishwakarma

Akash is working as an Odoo developer with an overall 1+ years of experience. His areas of expertise are Python, Odoo, and MySQL. He is honest about his work.

Request for Proposal

Name is required

Comment is required

Sending message..