I am trying to print difference between 2 folders and files. It shows me the content are different but I want it to actually print the differences which are not present in other folder with same file name.
I have a script in which I used mmap to read the contents. So far it can show me which files are different but not actually printing the exact differences
import os
import mmap
def compare_files(file1: str, file2: str) -> bool:
"""Function to compare files."""
with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
size1 = f1.seek(0, 2)
size2 = f2.seek(0, 2)
if size1 != size2:
return False
if size1 == 0:
return True
with mmap.mmap(f1.fileno(), 0, access=mmap.ACCESS_READ) as mm1, \
mmap.mmap(f2.fileno(), 0, access=mmap.ACCESS_READ) as mm2:
return mm1[0:] == mm2[0:]
def compare_folders(folder1: str, folder2: str) -> None:
differences_found = False
# Compare files in folder1
for root1, dirs, files in os.walk(folder1):
for file in files:
file1 = os.path.join(root1, file)
root2 = root1.replace(folder1, folder2, 1)
file2 = os.path.join(root2, file)
if not os.path.isfile(file2):
print(f"File {file} exists in {root1} but not in {root2}")
differences_found = True
else:
# If the file exists in both folders, compare them
if not compare_files(file1, file2):
print(f"Files {file} differ in {root1} and {root2}")
differences_found = True
# Compare files in folder2
for root2, dirs, files in os.walk(folder2):
for file in files:
root1 = root2.replace(folder2, folder1, 1)
file1 = os.path.join(root1, file)
file2 = os.path.join(root2, file)
if not os.path.isfile(file1):
print(f"File {file} exists in {root2} but not in {root1}")
differences_found = True
if not differences_found:
print("No differences found between the files in the two folders.")
if __name__ == "__main__":
folder1 = input("Enter path to the first folder: ")
folder2 = input("Enter path to the second folder: ")
compare_folders(folder1, folder2)
I think you are looking for difflib