0

I want to match the filename by passing a list of substrings to avoid some files in loop if the string matches with the filename. Here's my code:

list_of_files = glob.glob('D:/folder/*.gz') # create the list of file
mylist=['abcd11','abcd12','jklm12','wxyz.12']
for file_name in list_of_files:
   for ind in df.index:
        if df['filename'][ind] in file_name: #filename column contains full file names 
            for i in mylist:
                if i not in file_name:
                    print(file_name)

The thing is, it is also returning filenames which are matching with those list items. following code is working if I pass only one substring in for loop, but I want to match multiple substrings to avoid multiple files.

list_of_files = glob.glob('D:/folder/*.gz') # create the list of file
for file_name in list_of_files:
   for ind in df.index:
        if df['filename'][ind] in file_name: #filename column contains full file names 
            if 'abcd11' not in file_name:
                    print(file_name)

Sorry if this kind of question is already been asked. Thank you!

1 Answer 1

1

Your code should be like this:

list_of_files = glob.glob('D:/folder/*.gz') # create the list of file
mylist=['abcd11','abcd12','jklm12','wxyz.12']
for file_name in list_of_files:
   for ind in df.index:
        if df['filename'][ind] in file_name: #filename column contains full file names 
            is_in_list = False
            for i in mylist:
                if i in file_name:
                    is_in_list = True
            if not is_in_list:
                print(file_name)

The problem with your code is that if the condition:

if i not in file_name:

Is satisfied for one of the elements in mylist, then it will print the name of the file. Whereas, what you want is that it is satisfied for all elements in mylist.

Sign up to request clarification or add additional context in comments.

1 Comment

Hello, @Bruno Mello Thanks for your time! I tried the above code but this one also satisfied for one element (first in the loop) in mylist instead for all elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.