1

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 out.

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

for x in range (len(word)):
    if word[x] in file_list:
       #print the file name

This is part of the code but unable to continue after some searches. I need the full name that match the word to print out.

6 Answers6

1

Try this -

for w in word:
     for file in file_list:
         if w in file:
             print file
kuro
  • 3,214
  • 3
  • 15
  • 31
1

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 for i in file_list for b in word if b in i]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
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]
...     if any(name.endswith(tail) for tail in word):
...         print(name)
... 
h_ABC_U12
h_GGG_U13
h_HVD_U14
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

Surely

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

Would do the job?

Henry
  • 1,646
  • 12
  • 28
0

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 for file_name in file_list if next((w for w in word if w in file_name), None)]
Vsevolod Kulaga
  • 666
  • 7
  • 8
0
word = ['U12','U13','U14']
file_list = ['h_ABC_U12.csv','h_GGG_U13.csv','h_HVD_U14.csv','h_MMMB_U15.csv']

for file_name in file_list:
  for w in word:
    if w in file_name:
      print(w,file_name)

RESULT

U12 h_ABC_U12.csv
U13 h_GGG_U13.csv
U14 h_HVD_U14.csv
Fuji Komalan
  • 1,979
  • 16
  • 25