Kevin R.
Kevin R.

Reputation: 602

Comparing names of two files in different directories

So I am going through two directories. For each file found, I print their name. What I want to do is make a comparison, but I can't advance since I'm having trouble with my if statement. Let's say I have a txt file named some in both directories.If some is found in the file name, i print found. That works seperately. My problem is the and operator. Both files are named "some.txt", but I get nothing. Like I said, it works if I get rid of the and operator.

def compare(directory1, directory2):
    for file1, file2 in zip(os.listdir(directory1),(os.listdir(directory2))):
        if "some" in file1 and "some" in file2:
            print("found")

Upvotes: 0

Views: 82

Answers (2)

Prashant
Prashant

Reputation: 306

This is one way to do it, I believe:

def compare(directory1, directory2):
dir1 = {file for file in os.listdir(directory1)}
dir2 = {file for file in os.listdir(directory2)}
dir_common = dir1.union(dir2)
for file in dir_common:
    if "some" in file:
        print("found")

Upvotes: 1

DevShark
DevShark

Reputation: 9112

Do not use zip in this case. The way you are doing it, you are only comparing file1 and file2 that have the same index in your directory list.

To compare all possible pairings, simply do this:

def compare(directory1, directory2):
    for file1 in os.listdir(directory1):
        for file2 in os.listdir(directory2):
            if "some" in file1 and "some" in file2:
                print("found")

Upvotes: 1

Related Questions