Search code examples
pythonlistglob

How can I search for files based on elements of a list?


I have a list tile with elements like these

G11451-11500
G11501-11550
G11551-11600
G11601-11650

Which I want to use to search a directory and store the files in a list.

For example, this : glob.glob('*G11451-11500*.sh')gives me the intended output with a list of filenames.

But I want to do this in a loop. And I am unable to proceed from here:

for ix in tile:
        e = glob.glob('*format(ix)*')

Solution

  • Use str.format and pass ix into the string:

    e = glob.glob('*{}*.sh'.format(ix))
    

    If you're reading these strings from some external source (such as a file), ensure you've removed the trailing newlines with str.strip.