Skip to content Skip to sidebar Skip to footer

Python: How To Find The Element In A List Which Match Part Of The Name Of The Element

I have a list of keyword to find from a list of file name. Example, if the keyword is 'U12', I want to find the csv file that contain 'U12' which is 'h_ABC_U12.csv'and print it ou

Solution 1:

I suggest using os.path.splitext to get the filename without extension.

>>>from os.path import splitext>>>for f in file_list:...    name = splitext(f)[0]...ifany(name.endswith(tail) for tail in word):...print(name)... 
h_ABC_U12
h_GGG_U13
h_HVD_U14

Solution 2:

Try this -

for w in word:for file in file_list:if w in file:printfile

Solution 3:

You can try this using list comprehension:

word = ['U12','U13','U14']
file_list =['h_ABC_U12.csv','h_GGG_U13.csv','h_HVD_U14.csv','h_MMMB_U15.csv']

print [i foriin file_list forbin word if b in i]

Solution 4:

Surely

for x in range(len(word)):
    for file in file_list:
        if x in file:
            print file

Would do the job?

Solution 5:

This should perform better:

for file_name in file_list:
    the_word = next((w for w in word if w in file_name), None)
    if the_word:
        print the_word
        print file_name

Or to get the list of all file names:

[file_name forfile_namein file_list ifnext((w forwin word if w in file_name), None)]

Post a Comment for "Python: How To Find The Element In A List Which Match Part Of The Name Of The Element"