Source From Here
Question
This is what I have:
but I want to search the subfolders of src. Something like this would work:
But this is obviously limited and clunky.
HowTo
Use pathlib.Path.rglob from the the pathlib module, which was introduced in Python 3.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. For older Python versions, use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:
This is what I have:
- glob(os.path.join('src','*.c'))
- glob(os.path.join('src','*.c'))
- glob(os.path.join('src','*','*.c'))
- glob(os.path.join('src','*','*','*.c'))
- glob(os.path.join('src','*','*','*','*.c'))
HowTo
Use pathlib.Path.rglob from the the pathlib module, which was introduced in Python 3.5.
- from pathlib import Path
- for path in Path('src').rglob('*.c'):
- print(path.name)
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. For older Python versions, use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:
- import fnmatch
- import os
- matches = []
- for root, dirnames, filenames in os.walk('src'):
- for filename in fnmatch.filter(filenames, '*.c'):
- matches.append(os.path.join(root, filename))