geodranic
geodranic

Reputation: 145

Excluding certain words found in list of files with list of exclusion terms

Trying to exclude certain terms from a list as shown below. I'm sure I'm missing something.

dir = r'C:\Temo'
exclude = ['test', 'Test', 'debug', 'Debug']

for item in exclude:
    new_list = [os.path.join(dir, files)
                for files in os.listdir(dir)
                if files.endswith(".csv") and item not in files]

This results in excluding only 1 term from the exclude list, although the others are present. I'm sure I'm missing something simple

Upvotes: 1

Views: 111

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195573

You can use all() in list comprehension to filter out items. Also, you can use str.lower to not include all variations of file-names (lower/upper-case):

import os

dir = r'C:\Temo'
exclude = ['test', 'debug']

new_list = [os.path.join(dir, file)
            for file in os.listdir(dir)
            if file.endswith(".csv") and all(ex not in file.lower() for ex in exclude)]

print(new_list)

Upvotes: 1

Related Questions