Search code examples
glob

How to get specific files with glob.glob when they have similar numbers?


I have files with similar numbers in them, for example:

13Aug2015_01blue.txt, 13Aug2015_02blue.txt, 13Aug2015_12blue.txt, 13Aug2015_13blue.txt... etc.

I want to use glob.glob to only extract the file that has 01 and 12... When I use

loc1=glob.glob('*[01,12]*.txt')

I get back all the files because most of them have number 0-2 in them. So is there a syntax that let's me only extract the files with EXACTLY 01 and 12?


Solution

  • You can specify your search further by including the preceding underscore and choosing files with _01 and _12 instead of 01 and 12. I have never used the bracket syntax, but my understanding is that it is meant to match a range for single character and not several. You may have better luck just creating the loc1 array from two glob searches:

    loc1_01 = glob.glob('*_01*.txt')
    loc1_12 = glob.glob('*_12*.txt')
    

    or if you want a single line of code:

    loc1 = [glob.glob('*_01*.txt')[0], glob.glob('*_12*.txt')[0]]