Search code examples
pythonregexglob

how can I use a particular regex with glob


I have a folder called example and it has several folders in it like ABC, BC, ABCD, etc. Folder name varies from 2-4 letters. in each folder, it has different files. For ABCD, it has ABCD-circle.txt, ABCD-circle-square.txt, ABCD-square.txt. same for other folders like for BC, it has BC-circle.txt,BC-circle-square.txt, BC-square.txt.

I want to get only the circle.txt for each folder i.e. ABCD-circle.txt, BC-circle.txt.

I tried using glob path in python

local =  glob.glob('/Users/tp/Downloads/example/*/[A-Z]*-circle.txt')

but here I am getting all files BC-circle.txt,BC-circle-square.txt,ABCD-circle.txt,ABCD-circle-square.txt.

and if I do

  local =  glob.glob('/Users/tp/Downloads/example/*/[A-Z]{2,4}-circle.txt')

then I am getting nothing. Please advice!!


Solution

  • I did the following:

    local =  glob.glob('/Users/tp/Downloads/example/*/[A-Z]*-circle.txt')
    for filePath in local:
        matches = re.findall("[A-Z]{2,4}-circle.txt", filePath)
        if matches:
            print(filePath)
    

    and that worked!