Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to glob for files recursively in python

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.

like image 224
David Parks Avatar asked Nov 16 '25 08:11

David Parks


1 Answers

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
                  https://stackoverflow.com/revisions/49022163/1

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

like image 79
wim Avatar answered Nov 17 '25 23:11

wim