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.


 

Syntax:


 

Suppose we need to read a file then:


 

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


 

Example:

 

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

print(file.read())


 

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.


 

Example:


 

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

print(file.readline())
f
ile.close()


 

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 compare.py 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)

      else:

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

# Close File

file1.close()

file2.close()


 


 

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..