import os
def compare_files(file1, file2):
# Function to compare files
pass
def compare_folders(folder1, folder2):
differences_found = False
# Compare files in folder1
for root, dirs, files in os.walk(folder1):
for file in files:
file1 = os.path.join(root, file)
file2 = os.path.join(root.replace(folder1, folder2, 1), file)
if not os.path.exists(file2):
print(f"File {file} exists in {folder1} but not in {folder2}")
differences_found = True
elif os.path.isfile(file2):
# If the file exists in both folders, compare them
compare_files(file1, file2)
# Compare files in folder2
for root, dirs, files in os.walk(folder2):
for file in files:
file1 = os.path.join(root.replace(folder2, folder1, 1), file)
file2 = os.path.join(root, file)
if not os.path.exists(file1):
print(f"File {file} exists in {folder2} but not in {folder1}")
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 am trying to compare the files in both folders and print out the contents which are different from each other. As well the file name which are different in both folders
There are several issues with the code:
compare_filesis not currently doing any comparison. It should compare the two input files first for size and only then check whether the contents are the same. It should return True or False according to whether the files compare equal and that return value should be used to setdifferences_found.I believe this should be:
This not only prints out the full paths to the files starting from the initial folders but also corrects a small bug: What if we have file folder1/a/b/test but folder2/a/b/test exists but it is a directory instead of a file. Your current would not show that file test exists in one directory but not the other and will not have set the
differences_foundflag.I have provided an implementation of
compare_filesin the complete code below:The above code works for me, so if you are still having difficulties, you need to explicitly show minimal directory structures that are not producing the results you expect along with what your expected result is and what you actually display.