Exercise
File Content Comparer
Objective
Develop a Python program to compare two files (of any type) and determine if they are identical (i.e., have the same content).
Example Python Exercise
Show Python Code
# Python program to compare two files and check if they are identical
def compare_files(file1, file2):
try:
# Open both files in binary mode for comparison
with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
# Read the contents of the files
file1_data = f1.read()
file2_data = f2.read()
# Compare the contents of both files
if file1_data == file2_data:
print(f"The files '{file1}' and '{file2}' are identical.")
else:
print(f"The files '{file1}' and '{file2}' are not identical.")
except FileNotFoundError:
print(f"Error: One or both of the files '{file1}' or '{file2}' do not exist.")
except Exception as e:
print(f"Error: {str(e)}")
# Example usage
compare_files('file1.txt', 'file2.txt')
Output
When running the program with two identical files:
The files 'file1.txt' and 'file2.txt' are identical.
When running the program with two different files:
The files 'file1.txt' and 'file2.txt' are not identical.
Error Scenarios:
File Not Found:
Error: One or both of the files 'file1.txt' or 'file2.txt' do not exist.
General Errors:
Error: [Error message]
Share this Python Exercise
More Python Programming Exercises of Managing Files
Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.
In this exercise, you will develop a Python program to decode and display a Netpbm image file. This exercise is perfect for practicing file handling, string ma...
In this exercise, you will develop a Python program to extract only the alphabetic characters contained in a binary file and dump them into a separate file. This e...
In this exercise, you will develop a Python program to create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 ro...
In this exercise, you will develop a Python program to create a utility that censors text files. This exercise is perfect for practicing file handling, string ...
In this exercise, you will develop a Python program to parse SQL INSERT commands and extract their data into separate lines of text. This exercise is perfect f...
In this exercise, you will develop a Python program to create a utility that reads and displays images in the PGM format, which is a version of the NetPBM image forma...