Search code examples
pythonfileglob

How to print to the path of the file in python using glob


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.


Solution

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