Compare multiple file names in 2 different directory

647 views Asked by At

I have 2 folders (Ex1, Ex2), where folder Ex1 contains 2500 files and folder Ex2 contains 2300 files. Some of the files in folder Ex2 contains same content as of folder Ex1, I am trying to:

  • Compare the title of files in both the directories
  • Compare the content from each individual file from both directories
  • Compare the size[in bytes] of individual file in both directories.

If the above condition matches, the matched files are to be renamed with prefix "copied" followed by the file name in folder Ex2.

If the conditions do not match, the files are to be moved to folder Ex2 and renamed with prefix "new" followed by the file name.

So far, I have written the code to match individual file names in both directories. However, upon doing several research and correct syntax, I am failing to execute the program.

I assume the approach is not valid to solve this problem. Would anyone be kind enough to suggest a better approach and provide assistance to solve this problem?

## Code for files in example1
path = "C:/Users/OneDrive/Example1"
dir_list = os.listdir(path)
print(dir_list)

## code for files in example2
path2 = "C:/Users/OneDrive/Example2"
dir_list2 = os.listdir(path)
print(dir_list2)

comp2=None

#Iterate through the files in both the folder
for f in dir_list:
    for h in dir_list2:
        if comp2 = [filecmp.cmp(f,h, shallow= true)] is True:
            print(comp2)
1

There are 1 answers

8
martineau On

Here's valid syntax that does what I think you intended in that section of the code. It makes use of an assignment expression, something that was introduced in Python 3.8.

...

#Iterate through the files in both the folder
for f in dir_list:
    for h in dir_list2:
        if (comp2 := filecmp.cmp(f, h, shallow=True)):
            print(comp2)