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())
file.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()
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Aakash Vishwakarma
Aakash Vishwakarma is a highly skilled backend developer with years of industry experience. He has a comprehensive understanding of the latest technologies and practical experience working with tools and frameworks like Python Django, Django Rest Framework, Odoo14, Odoo15, HTML, CSS, JavaScript, and Jquery, as well as databases. He has contributed to the successful delivery of various client projects, including Pando Mall, Hatrik Marketplace, My Mandi, File Comparison, and TRO Projects. Aakash has a creative mindset and strong analytical skills that enable him to think critically and explore new technologies with ease, making him an asset to any project