1

I want to find the file name and then print the path of that file using python. My program runs successfully as follows.

from pathlib import Path
import glob
import os


for file in Path('<dir_address>').glob('**/*some_string*.*fastq.gz'):
    print(file)

It print the paths of all the files having some_string matching in its name in the .

Now I want to define an argument in place of some_string as follows.

file_name="abc"   

from pathlib import Path
import glob
import os


for file in Path('<dir_address>').glob('**/*file_name*.*fastq.gz'):
    print(file)

It doesn't give any output. My questions is how to give this sub_string as a variable in a program which will bring the files path of all the files having this specific sub_string in their name.

Sid
  • 2,174
  • 1
  • 13
  • 29
Stupid420
  • 1,347
  • 3
  • 19
  • 44
  • Have you considered using regex, as opposed to glob - as mentioned in [this post](https://stackoverflow.com/a/13032338/6340496)? Then, you can use the `re.compile()` function to store the compiled regex into a variable, as you've asked. – S3DEV Sep 20 '19 at 07:42
  • 1
    I need confirmation, what you want is all file path of all filenames with the substring of _abc_ ? Am I right? – CodeRed Sep 20 '19 at 07:44
  • yes. All files path with a substring abc – Stupid420 Sep 20 '19 at 07:45
  • 2
    you have string so use string function like string formatting `f'**/*{argument}*.*fastq.gz'` or for older Python `'**/*{}*.*fastq.gz'.format(argument)` – furas Sep 20 '19 at 07:47

1 Answers1

1

I think this is what you need:

from pathlib import Path
import glob
import os

file_name="abc"   
for file in Path('<dir_address>').glob(f'**/*{file_name}*.*fastq.gz'):
    print(file)

In the f-string {filename} gets replaced by the string of the variable filename.

AnsFourtyTwo
  • 2,480
  • 2
  • 13
  • 33