-2

Let us assume there is a folder X and then a folder Y, I would like to go to both "folder X" and "folder Y" and compare the file names 1 by 1 using python language. How would I do that? I tried using the following code:

for f in dir_list: # iterates through the folder X and look for files in Folder X
    for h in dir_list2: # iterates through the folder Y and look for files in Folder Y
        name = os.path.basename(f) # returns every file names
        name2= os.path.basename(h)
        if (name==name2):
            print("its a match")
        else:
            print("nope, does not match") # My all files match, 
# but I got output saying they do not match. 

# Not sure why would it say not a match even though they are all same files in Folder X and Folder Y

# Can someone suggest a better way to compare files names from 2 folders?

The above code prints the name of every file in folders and results some files as "Not a match", even though they are same files. Instead of printing every file, how do I make it show the name of files that do not match and the ones that do match?

Karl Knechtel
  • 56,349
  • 8
  • 83
  • 124
Smit Shah
  • 13
  • 5
  • Currently you are comparing every single file in dir_list to **every** single file in dir_list2. – SuperStormer May 30 '22 at 17:38
  • Yes, that is the plan. @SuperStormer – Smit Shah May 30 '22 at 17:39
  • ie. if `dir_list` is `["a", "b", "c"]` and `dir_list2` is `["a", "b","c"]`, you're comparing: a-a, b-a, c-a, a-b, b-b, c-b, a-c, b-c, c-c. – SuperStormer May 30 '22 at 17:41
  • "and results some files as "Not a match"" Okay, so if you have two identical lists `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]` and `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`, and you compare every element to every other element, how many times do you expect to see a match? How many times do you expect to see a non-match? How many comparisons do you expect it to make in total? Do you see the problem? – Karl Knechtel May 30 '22 at 17:45
  • @SuperStormer thank you for the comment, I see, it should be `[a-a, b-b]` and not `[a-b,b-a]` – Smit Shah May 30 '22 at 18:04
  • @KarlKnechtel There should be one check for each file, so `[1,2,3,4,5,6,7,8,9]` and `[1,2,3,4,5,6,7,8,9]`, it should only look for file 1 in other folder. So here there should be only 1 match for file 1 i.e `[1]` and `[1]` – Smit Shah May 30 '22 at 18:07
  • Right. My point is that the way your code works now, it will check: is `1` from the first list equal to `1` from the first list? Okay. But let's keep going: is `1` from the first list equal to `2` from the first list? No. Equal to `3`? No. It will report *all* of those results, for *each* item in the first list. If there are 10 in each list, that is 100 comparisons. – Karl Knechtel May 30 '22 at 19:52
  • Anyway, I quite like the duplicate that was turned up for this question, and I have a feeling there are some other old questions I should close as duplicates now. – Karl Knechtel May 30 '22 at 19:53

0 Answers0