Clean way to glob for files recursively in python


Keywords:python 


Question: 

Given the following directory structure:

myDir
   file1.c
   file2.c
   subDirA
      file3.c
   subDirB
      file4.c

I want to find *.c files with glob, or another similarly efficient method (not using the os.walk method documented elsewhere).

The problem I encounter is that, given the path myDir I can't get all c files recursively in one line of code.

glob.glob('myDir/*.c', recursive=True) 

only yields file1 and file2. And

glob.glob('myDir/**/*.c', recursive=True

only yields file3 and file4.

Is there a nice clean way to combine those two statements into one? It sure seems like there would be.


1 Answer: 

Using pathlib:

from pathlib import Path
Path('/to/myDir').glob('**/*.c')

As for why glob didn't work for you:

glob.glob('myDir/**/*.c', recursive=True)
             ^
             |___ you had a lower d here?

Make sure you're running it from within the parent of myDir and that your Python version is 3.5+.