This is what I have:
JavaScript
x
2
1
glob(os.path.join('src','*.c'))
2
but I want to search the subfolders of src. Something like this would work:
JavaScript
1
5
1
glob(os.path.join('src','*.c'))
2
glob(os.path.join('src','*','*.c'))
3
glob(os.path.join('src','*','*','*.c'))
4
glob(os.path.join('src','*','*','*','*.c'))
5
But this is obviously limited and clunky.
Advertisement
Answer
pathlib.Path.rglob
Use pathlib.Path.rglob
from the pathlib
module, which was introduced in Python 3.5.
JavaScript
1
5
1
from pathlib import Path
2
3
for path in Path('src').rglob('*.c'):
4
print(path.name)
5
If you don’t want to use pathlib, use can use glob.glob('**/*.c')
, but don’t forget to pass in the recursive
keyword parameter and it will use inordinate amount of time on large directories.
For cases where matching files beginning with a dot (.
); like files in the current directory or hidden files on Unix based system, use the os.walk
solution below.
os.walk
For older Python versions, use os.walk
to recursively walk a directory and fnmatch.filter
to match against a simple expression:
JavaScript
1
8
1
import fnmatch
2
import os
3
4
matches = []
5
for root, dirnames, filenames in os.walk('src'):
6
for filename in fnmatch.filter(filenames, '*.c'):
7
matches.append(os.path.join(root, filename))
8