0

I have a lookup file (file1.txt) which has a list of patterns to be searched.

Ex content of file1.txt

 dtdge_ddgaec
 daew_e2

I have to list out the files in a particular directory based on the pattern in file1.txt Ex: If a particular directory has the below-mentioned files

abdc_dtdge_ddgaec_09030.txt
odad_dwad_dadatge_daece_0869.txt
dadaf_dawa_dpidae_daew_e2_0901.txt
adydyaq_da9dad_dagda_dadge_0730.txt

I need to display only the files that match the pattern in file1.txt

Output:

abdc_dtdge_ddgaec_09030.txt
dadaf_dawa_dpidae_daew_e2_0901.txt

In Unix Scripting, I can read file1.txt line by line and using ls command i can match the pattern using grep command and display the desired output.

I'm new to Python and unable to find an easy solution. Can anyone help me with this?

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Raj
  • 1
  • 1

1 Answers1

2

You could try a solution using the glob module. Something like this, maybe:

import glob
import os.path

with open('file1.txt', 'r') as file1:
    patterns = file1.read().split()

matching_filenames = []
for pattern in patterns:
    matching_filenames += glob.glob(os.path.join(MY_DIR, '*' + pattern + '*'))
mostsquares
  • 834
  • 8
  • 27
  • 1
    Charlie, Thanks for the input. i was able to list out the files which are matching the pattern in a directory and display the content of it. – Raj Feb 05 '19 at 20:07